dsportesa
dsportesa

Reputation: 63

preg_replace, string and numeric replacement

So this is a preg_replace associated question i guess,

I have a string with multiple repeating patterns

they all formated as:

some string :22: more text :12: etc

how do i replace the ":" around them with some different char?

Upvotes: 0

Views: 221

Answers (3)

Matt
Matt

Reputation: 23729

EDIT: Misunderstood original question. However, is still a flexible option:

$result = str_replace(":22:", "tag", "some string :22: more text :12: etc");
$result = str_replace(":12:", "other_tag", $result);

Replace the ? character with your replacement character.

Upvotes: 0

JRL
JRL

Reputation: 77995

Sbustitudes _ for : around numbers:

preg_replace('/:(\d+):/', '_$1_', 'some string :22: more text :12: etc');

Upvotes: 0

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22152

You can do something like this:

$string = 'some string :22: more text :12: etc';
$regex = '/:(\d+):/';
$newString = preg_replace($regex, "@$1@", $string);

Note: You have to replace the '@' in the second parameter with the char you want (also different chars before and after the numbers).

Upvotes: 1

Related Questions