开发者

PHP preg_replace [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

PHP str_replace

I have a string $html in which there is the text Greek and   multiple times. These need to be replaced by Alpha, Beta, Gamma, Delta, Epsilon in that order. Like this:

<?php
$html = "Greek blablabla &nbsp; Greek Greek blabla &nbsp;" //input
$html = "Alpha blablabla Beta Gamma Delta blabla Epsilon" //output
or
$html = "Greek blabla Greek Greek bla Greek Greek" //input
$html = "Alpha blabla Beta Gamma bla Delta Epsilon" //output
or
$html = "&nbsp; &nbsp; blablablabla &nbps; &nbsp; &nbsp;" //input
$html = "Alpha Beta blablablabla Gamma Delta Epsilon" //output
or ....
?>

It doesn't need to be solved with preg_replace but I think this is works开发者_运维问答 best with it.

Thanks again!


Short and to the point:

$input = '&nbsp; &nbsp; blablablabla &nbps; &nbsp; &nbsp;';

$replacements = array('Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon');
$index = 0;
$result = preg_replace('/(Greek|&nbsp;)/e', '$replacements[$index++]', $input);

print_r($result);

See it in action.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜