替换单词以php中的@开头

时间:2018-11-16 00:14:22

标签: php preg-replace

我想将以@开头的任何单词替换为另一个单词。

输入为我的值是@truth_word不好

$myword = "My value is @truth_word and bad";
$newtext = preg_replace("/^@/", "good" , $myword); 
echo $newtext; //My value is good and bad;

输出应为我的值是好是坏

1 个答案:

答案 0 :(得分:0)

您需要在字符串^之前的字符串开头(\s或空白字符(@)后面使用正号,然后输入一定数量的单词后面的字符(\w

$myword = "My value is @truth_word and bad";
$newtext = preg_replace("/(?<=^|\s)@\w+/", "good" , $myword); 
echo $newtext;

输出

My value is good and bad

Demo on 3v4l.org