cxForce
cxForce

Reputation: 9

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.:

In the end the string will be converted to:

"qqweblbookqppenq"

I have read read str_replace() 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?

Upvotes: 0

Views: 688

Answers (2)

deceze
deceze

Reputation: 521995

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

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

Upvotes: 1

amitchd
amitchd

Reputation: 975

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);

Upvotes: 0

Related Questions