3

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.

2 Answers 2

1

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');
?>
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I read strstr but it's strtr. That's the good answer! Thanks!
@nikic: What should be the answer if regex is required?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.