PHP replace string starting with xxx and ending with yyy after 5 characters

Viewed 86

Input:

$str = 'hi test1="12c4 ab3d" blablabla test1="5678 sdfg"'

So I need to remove string between 'test1="' and '"' after 5 characters, like that:

'hi test1="12c4" blablabla test1="5678"'

I already tried:

$str= preg_replace('/test1="[\s\S]+?"/', 'test1=""', $str);

But my ouput was:

'hi test1="" blablabla test1=""'
2 Answers

Alternatively, without a regex and using simple strpos() and substr()

$str = 'hi test1="12c4 ab3d" blablabla test1="5678 sdfg"';

$find = 'test1=';
$p1 = stripos($str, $find) + strlen($find)+5;
$p2 = strripos($str, $find) + strlen($find)+5;

$new =  substr($str, 0, $p1) . substr($str, $p1+5, $p2-$p1-5) . substr($str, $p2+5);
echo $new . PHP_EOL;

You can use

$str = 'hi test1="12c4 ab3d" blablabla test1="abcd 3456 sdfs 2435"';
echo preg_replace('~\btest1="[^"\s]*\K[^"]+~', '', $str);
// => hi test1="12c4" blablabla test1="abcd"

See the PHP demo and the regex demo.

Details:

  • \b - a word boundary
  • test1=" - a literal text
  • [^"\s]* - zero or more chars other than whitespace and "
  • \K - match reset operator that removes the text matched so far from the match memory buffer
  • [^"]+ - one or more chars other than ".
Related