开发者

preg_replace not working :(

开发者 https://www.devze.com 2023-01-26 16:24 出处:网络
OK so I have this PHP script: <?php $stringz = \"Dan likes to eat pears and his favorite color is green!\";

OK so I have this PHP script:

<?php

$stringz = "Dan likes to eat pears and his favorite color is green!";
$patterns = array("/pears/","/green/");
$string = preg_replace($patterns, '<b>\\1</b>', $stringz);
echo "<textarea rows='30' cols='100'>$string</textarea>";

?>

and when I run it I get this: Dan likes to eat <b></b> and his fa开发者_高级运维vorite color is <b></b>!

The is suppose to have a word in it... but it doesn't...


That's because you aren't explicitly capturing anything. \\0 captures the entire match, of course, but in order to capture specific parts, you need to use capturing groups if you want to use \\1, \\2, \\3, etc. Change $patterns to this:

 $patterns = array("/(pears)/","/(green)/");

()'s denote capturing groups, and whatever value is captured inside of them is stored in the reference \\n, where \\n refers the the 1-indexed nth capturing group.


Change \\1 for \\0.


How about

$patterns = array("/(pears)/","/(green)/");

?

\\1 applies to a subject, which is whatever you have in parentheses.

0

精彩评论

暂无评论...
验证码 换一张
取 消