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.

Example is below:
<? $data = ‘abcdef abcdef abcdef’; // pattern, replacement, string, limit

echo preg_replace(‘/abcd/’, ‘webtechsource’, $data, 1); // outputs ‘webtechsourcedef abcdef abcdef’ ?>

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

<? $data = ‘abcdef abcdef abcdef’; // pattern, replacement, string

echo ereg_replace(‘abc’, ‘webtechsource’, $data); // outputs ‘webtechsourcedef webtechsourcedef webtechsourcedef’ ?>

Replace hyphen (-) with comma (,) in php

We can use PHP function str_replace().

<?php
$string = “Jul 15 ‐ 07 & 14 ‐ 15”;
$string = str_replace(“‐”,”,”,$string);
echo $string;

// This will output: “Jul 15 , 08 & 14 , 15”
?>

 

There is more you can do with str_replace() check out the PHP manual for more info: http://php.net/manual/en/function.str-replace.php

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – we are here to solve your problems.

I, Dayanand Saini,the founder and chief editor of www.webtechsource.com,have been working as a software engineer from last 4+ years. It's my hobby to learn new things and implement on live environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

67 − 66 =

%d bloggers like this: