开发者

PHP, regular expression and preg_replace, need some help

开发者 https://www.devze.com 2023-03-30 06:08 出处:网络
I need help with little replacing: Some text [ id ] to... Some text | id I\'m new in regular expression and I just don\'t know, how to safely keep text inside [ ]... And I don\'t want to use str

I need help with little replacing:

Some text [ id ]

to...

Some text | id

I'm new in regular expression and I just don't know, how to safely keep text inside [ ]... And I don't want to use str_repla开发者_如何学Goce and trim... I have to use expressions (don't ask why :D )... Can somebody help me?


This should work for non-nested square brackets:

preg_replace("/\[(.*?)\]/", "|$1", "Some text [ id ]")

OUTPUT

Some text | id


You don't need a regex for such a simple task, str_string() will do it.

$str = str_replace(array("[","]"), array("|", ""), $str);

OUTPUT

Some text | id

Using regex to do something like this is like asking Einstein to solve 2 + 2.

0

精彩评论

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