PHP replace only first occurrence of a string match.

How to replace only the first occurrence of a string in php.

Say you wanted to only replace the first occurrence of a string match instead of all occurrences You would use php preg_replace function to do the trick.

The code is below:

<?
$var = 'abcdef abcdef abcdef';
// pattern, replacement, string, limit
echo preg_replace('/abc/', '123', $var, 1); // outputs '123def abcdef abcdef'
?>

Just incase you wanted to still match all occurrences, just use the php function erag_replace.
The code is below:


<?
$var = 'abcdef abcdef abcdef';
// pattern, replacement, string
echo ereg_replace('abc', '123', $var); // outputs '123def 123def 123def'
?>

Please rate this post by clicking a star:

(3 votes, average: 5.00 out of 5)

Leave a Reply





Tags: , , , , , , , ,