I am trying to str_replace a string like (infobox tbs7) with a string like something with tbs7. But i want it to work even when the tbs7 is something else. I have defined (infobox $) and something with $, but the $ should be be anything.
How do i do that?
CodePudding user response:
You could use Regular Expressions with preg_grep:
$source = '(infobox tbs7)';
$target = 'something with $2';
$pattern = '/^(\(infobox )(.*)(\))$/i';
$result = preg_replace($pattern, $target, $source);
The regex pattern 'splits' the source string into three pieces:
'(infobox ' -> $1
'anything in between' -> $2
')' -> $3
and $2 is used in the replacement string to indicate what to replace.
CodePudding user response:
Try replacing the pattern \binfobox \S
with infobox
followed by the replacement word:
$input = "Here is infobox tbs7 and other things.";
$output = preg_replace("/\binfobox \S /", "infobox abc", $input);
echo $output; // Here is infobox abc and other things.