-2

I have a string like

some text for test and need to replace by regex using php
we have extra sentence too

I need to replace the sentence before the word regex

I need a result of

using php
we have extra sentence too

Replace some text for test and need to replace by regex by ""

Toto
  • 89,455
  • 62
  • 89
  • 125
Naveen K
  • 859
  • 4
  • 14
  • 29

3 Answers3

2

PHP can use \K

Use this simple regex:

(?s)^.*?regex\K.*

See demo.

  • The (?s) allows the dot to match across several lines.
  • ^ asserts that we are at the beginning of the string.
  • .*?regex lazily matches everything up to regex
  • \K tells the engine to "Keep" everything it has matched so far out of the returned match (drop it)
  • .* matches everything else. This is the returned match.

In PHP, no need to replace. As the output of this php demo shows, you can just match:

$mystring = "some text for test and need to replace by regex using php.
We have another sentence";
$regex = '~(?s)^.*?regex\K.*~';
if (preg_match($regex, $mystring, $m)) {
    $yourmatch = $m[0]; 
    echo $yourmatch;
    } 

Let me know if you have any questions. :)

zx81
  • 41,100
  • 9
  • 89
  • 105
0

You don't need regex for this. You can use substr() and strpos():

$str = substr($str, strpos($str, 'regex') + 6);

See demo

Mark Miller
  • 7,442
  • 2
  • 16
  • 22
0

The below regex will match only the characters which are just after to the string regex,

/(?<=regex\s)(.*)/s

DEMO

Your PHP code would be,

<?php
$mystring = "some text for test and need to replace by regex using php.
We have another sentence";
$regex = '~(?s)(?<=regex\s)(.*)~';
if (preg_match($regex, $mystring, $m)) {
    $yourmatch = $m[0]; 
    echo $yourmatch;
    }
?>

Output:

using php.
We have another sentence

Explanation:

(?s)              #  Allows . to match anything(including newlines)
(?<=regex\s)(.*)  #  Positive lookbehind is used. It matches anything after the string regex followed by a space.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • You don't need to add `s` and `m` modifiers into every regex. They [do different things](http://stackoverflow.com/a/24249564/1438393). Here you only need the `s` modifier :) – Amal Murali Jun 21 '14 at 07:10