PHP match string and get the rest?
4 answers
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 share
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 to share