Php 用不同的替换件替换每一次发生的事件
我有一个字符串,看起来像这样:Php 用不同的替换件替换每一次发生的事件,php,Php,我有一个字符串,看起来像这样: $post = "Test $asd$ lol test asd $test$"; 我希望它成为: $post = "Test [bb]asd[/bb] lol test asd [bb]test[/bb]"; 哪种方法最简单/最好?请注意,$出现的次数有时会有所不同。基本思想是用[b]分别替换其他每一个事件[/bb] 我希望你能理解。试试这个: <?php $str = $post = 'Test $asd$ lol test asd $test$'
$post = "Test $asd$ lol test asd $test$";
我希望它成为:
$post = "Test [bb]asd[/bb] lol test asd [bb]test[/bb]";
哪种方法最简单/最好?请注意,$出现的次数有时会有所不同。基本思想是用[b]分别替换其他每一个事件[/bb]
我希望你能理解。试试这个:
<?php
$str = $post = 'Test $asd$ lol test asd $test$';
echo preg_replace('/\$(\w+)\$/','[bb]$1[/bb]',$str);
?>
您正在一个双引号“文本块中使用一个
$
符号。PHP将假定这些是变量名,并且很可能会出错。请确保使用(\w+?)或([^$]+)进行延迟匹配-后者更好,因为它也可以捕获断字输入;即,您可以匹配$lol!$
(但请确保没有其他选项)$“在字符串中,使用单引号输入,如上面的@Kami notes)
Test [bb]asd[/bb] lol test asd [bb]test[/bb]