开发者

how do I replace certain characters in a string?

Suppose I have 开发者_开发知识库a string like this

SOMETHING [1000137c] SOMETHING = John Rogers III [SOMETHING] SOMETHING ELSE

and I need to turn it into this

SOMETHING [1000137c] SOMETHING = John_Rogers_III [SOMETHING] SOMETHING ELSE

Therefor I need to replace spaces with "_" between words after "[1000137c] SOMETHING = " and before " [". How can I do that in php?

Thanks!


$s = "SOMETHING [1000137c] SOMETHING = John Rogers III [SOMETHING] SOMETHING ELSE";
$a = split(" = ",$s,2);
$b = split(' \[',$a[1],2);
$s = $a[0] . ' = ' . strtr($b[0],' ','_') . ' [' . $b[1];

print_r($s);

produces:

SOMETHING [1000137c] SOMETHING = John_Rogers_III [SOMETHING] SOMETHING ELSE


$arr = split a string in an array on "=" and then

str_replace(" ", "_", $arr[1])


using a regex like so "/^[\w ]+[[\w\d]+] [\w]+ = ([\w\d ]+) [[\w\d]+] [\w ]+$/i" should return match 1 as "John Rogers III", though this based on the current example.

using preg_replace_callback with the above regex, you can str_replace to replace the spaces with underscores in the callback function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜