Replace only the first occurance in a string

Although you can't do this with ereg_replace, you can use preg_replace instead:

$var = 'abcdef abcdef abcdef';

// pattern, replacement, string
echo ereg_replace('abc', '123', $var); // outputs '123def 123def 123def'

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

You might also like...




Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Better train people and risk they leave – than do nothing and risk they stay.” - Anonymous