1

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
  • Please, Post code you have tried Commented Jan 6, 2014 at 6:02
  • 1
    It is not very clear what you asking. Looks like it could be done with bare string search. Try to provide clear example and exact logical description of your problem. Commented Jan 6, 2014 at 6:02
  • 1
    How about this trim(str_replace("Men improve", "","Men improve with the years")); Commented Jan 6, 2014 at 6:02
  • Don't forget to trim the results Commented Jan 6, 2014 at 6:03

4 Answers 4

2

Can you try this,

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

 //OP - with the years
Sign up to request clarification or add additional context in comments.

Comments

2

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
  • \s is a shorthand for any kind of white-space, * any amount of
  • i the 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

1

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);
?>

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

Comments

1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.