PHP match string and get the rest?

Let's say I have a phrase: "Men get better over the years" then if I provide a line that corresponds to "Men get better" I only want the rest "over the years". Is this possible with regex?

+1


source to share


4 answers


If you really want to use regex as the question asked, ask the question, here is some code you can start.

<?php 
$str = "Men improve with the years";
$regex = "/Men improve/";

echo preg_replace($regex, "", $str);
?>

      



ref: http://php.net/manual/en/ref.pcre.php

+1


source


Can you try this,



trim(str_replace("Men improve", "","Men improve with the years"));

 //OP - with the years

      

+2


source


If you want to replace $needle

with the beginning $haystack

using preg_replace :

$needle = "Men improve";
$haystack = "Men improve with the years";

echo preg_replace('/^'.preg_quote($needle).'\s*/i', "", $haystack);

      

  • /

    - delimiter
  • ^

    the caret matches the position before the first character in the line
  • preg_quote exits$needle

  • \s

    is the shorthand for any kind of space, *

    any number
  • i

    ignoreCase modifier after the final delimiter makes the pattern case insensitive

To only match if there is a word boundary after $needle

change the pattern to:

'/^'.preg_quote($needle).'\b\s*/i'

      

+2


source


To achieve this kind of task, we will have many ways, in the end we need to choose one of the methods that will be suitable for our requirement, this is one of my approaches

$str = "Men improve with the years";
$substr = "Men improve ";
$result = substr($str, strlen($substr), strlen($str) - 1);
echo trim($result);

      

+1


source







All Articles