开发者

preg_replace conditional replacement with different string

I know there's a if/then in the matching of regular expressions, but is there one in the replace?

ie. I want to do in one regex

"I have Foo Bars under $5 for sale" to be "Foo Bars~$5"

"I have Foo Bars for sale" to become "Foo Bars" and NOT "Foo Bars~"

I have an expression a bit like this at the moment:

preg_replace("/(([A-Z][a-z]*\s){1,3})((und开发者_高级运维er .)\d+)?/","$1~$4",$str);

(with other bits to remove the other text aswell of course!) but that includes the ~ even when there's no 'under' in it.

I could probably use preg_replace_callback but that seems a bit OTT

Thanks.


Php's trim function would do:

// Before: "Foo Bars~$5"
    $str = trim($str,'~');
// After: "Foo Bars~$5"

// Before: "Foo Bars~"
$str = trim($str,'~');
// After: "Foo Bars"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜