Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_replace array but only in the initial string

Tags:

regex

php

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.

like image 731
user721730 Avatar asked Feb 11 '26 19:02

user721730


1 Answers

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');
?>
like image 54
Bojan Kogoj Avatar answered Feb 14 '26 08:02

Bojan Kogoj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!