user721730
user721730

Reputation: 488

php preg_replace array but only in the initial string

This scripts

<?php
$pat = array ( '/A/', '/B/');
$rep = array ( 'B', 'C');
print preg_replace($pat, $rep, 'AAB');
?>

I would liket to print 'BBC' ('B' replaces 'A' and 'C' replaces only the initials 'B')

But it prints 'CCC' ('B' replaces 'A' and 'C' replaces 'B' and the 'A' previously replaced by 'B')

If I tried something like this script

<?php
$pat = array ( '/A/', '/B/');
$rep = array ( 'B', 'C');
print preg_replace($pat, $rep, 'AAB', 1);
?>

But it prints 'CAB'...

Thanks.

Upvotes: 3

Views: 238

Answers (2)

NikiC
NikiC

Reputation: 101936

If that really is all you want (only replace single characters), just use strtr:

$str = strtr($str, 'AB', 'BC'); // means: replace A with B and replace B with C

If you are not talking just about single characters, but about strings (but still no regex), strtr will still work:

$str = strtr($str, array('Hallo' => 'World', 'World' => 'Hallo'));

Upvotes: 1

Bojan Kogoj
Bojan Kogoj

Reputation: 5649

This should work :) You just change it's order, so it replaces B before A, and that's it

<?php
$pat = array ( '/B/', '/A/');
$rep = array ( 'C', 'B');
print preg_replace($pat, $rep, 'AAB');
?>

Upvotes: 1

Related Questions