Lets say I have the phrase: "Men improve with the years" then if I provide a string that matches "Men improve" I want to get the rest only "with the years". Is this possible with regex?
4 Answers
If you want to replace $needle at the start of $haystack using preg_replace:
$needle = "Men improve";
$haystack = "Men improve with the years";
echo preg_replace('/^'.preg_quote($needle).'\s*/i', "", $haystack);
/is the delimiter^caret matches the position before the first character in the string- preg_quote escapes the
$needle \sis a shorthand for any kind of white-space,*any amount ofithe ignoreCase modifier after the ending delimiter makes the pattern match case-insensitive
To match it only, if there is a word boundary after $needle modify the pattern to:
'/^'.preg_quote($needle).'\b\s*/i'
Comments
If you really want to use regex as the questioned asked, here is some code to get you started.
<?php
$str = "Men improve with the years";
$regex = "/Men improve/";
echo preg_replace($regex, "", $str);
?>
Comments
To achieve this type of task we will have many ways, finally we need to choose one of the method which will be suitable for our requirement, this is one my approach
$str = "Men improve with the years";
$substr = "Men improve ";
$result = substr($str, strlen($substr), strlen($str) - 1);
echo trim($result);
trim(str_replace("Men improve", "","Men improve with the years"));