开发者

How to replace characters in a string in PHP?

I have a problem in PHP. I've a string like this:

"qqslsqpsq"

And I want to replace every 's' with a separated value, e.g.:

  • First 's' -> pos: 2 -> 'web'
  • Second 's' -> pos: 4 -> 'book'
  • Third 's' -> pos: 7 -> 'pen'
  • ...

In the end the string will be converted to:

"qqweblbookqppenq"

I have read read str_r开发者_开发技巧eplace() is powerful, but it seems that can't do that. I'm thinking of finding the position of every 's' and replacing it with indexes, but I can't!!

Can you guide me? Is there any way to do this?


function replaceCallback() {
    static $i = 0;
    $replacements = array('web', 'book', 'pen');
    return $replacements[$i++];
}

echo preg_replace_callback('/s/',  'replaceCallback', 'ashreswfsb');


Using str_replace would mean you have to looop through the string and then use the offset of the first s found to decide where and what to replace. Instead, use preg_replace, to do this in a single statement.

$string = 'qqslsqpsq';
$string = preg_replace('/(.*?)s(.*?)s(.*?)s/', '${1}web${2}book${3}pen', $string);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜