简体   繁体   English

PHP:调整正则表达式以在每个单词的末尾添加一个字符

[英]PHP: Adjust regex to add a character at the end of every word

I have following regex: 我有以下正则表达式:

// Before: "Foo Bar Test";
$str = preg_replace( "/(^| )(\w)/", '$1+$2', $str );
// After: "+Foo +Bar +Test";

Is it possible to add the char "*" at the end of every word? 是否可以在每个单词的末尾添加字符“ *”?

The result I am looking for is: 我正在寻找的结果是:

// +Foo* +Bar* +Test*

Is it possible to do it in the same regex? 是否可以在同一个正则表达式中执行此操作? Or do I have to use a new one? 还是我必须使用一个新的?

You can do: 你可以做:

$str = preg_replace( "/(^| )(\w+)\b/", '$1+$2*', $str );

echo "$str\n";
//=> +Foo* +Bar* +Test*

Making 2nd captured group as (\\w+) will make it capture full word and putting * after $2 will place * at right place. 将第二个捕获组设为(\\w+)将使其捕获完整单词,并将*放在$2*放在正确的位置。

PS: You can also use lookbehind assertion : PS:您还可以使用后向断言

$str = preg_replace( "/(?<= |^)(\w+)\b/", '+$1*', $str );

to get the same output. 获得相同的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM