Page 1 of 1

how to replace string on first occurrence only

Posted: Mon May 25, 2009 12:45 am
by crishna369
I wanna know how i can replace a particular string only on first occurrence.
somebody plz reply.

Re: how to replace string on first occurrence only

Posted: Mon May 25, 2009 12:56 am
by mikemike
Try this:

Code: Select all

<?php
$var = 'weeeeeeeee weeeeeeeee abc 123 lets all do the abc, its easy as 123';
// pattern, replacement, string, limit
echo preg_replace('/abc/', '123', $var, 1); 
?>
Remember that you should only use preg_replace with reg exp as it's slower than normal replace functions.

Re: how to replace string on first occurrence only

Posted: Mon May 25, 2009 12:59 am
by requinix
If you want the (probably) faster string-based method, use strpos to find the first occurrence, strlen to know how much to remove, and substr_replace to do the replacement.


(Yeah, I know, not going to happen. mike posted code, I posted words. If someone is typing "plz" then there's no way they'll take the harder of the suggestions, regardless of any reasons why they should.)

Re: how to replace string on first occurrence only

Posted: Mon May 25, 2009 1:05 am
by mikemike
hehe :wink:

Re: how to replace string on first occurrence only

Posted: Mon May 25, 2009 1:06 am
by mikemike
I'm not convinced your method would be faster you know. I did some benchmarking on the regexp engine and normal replacement not so long ago and it's not that much slower.

Re: how to replace string on first occurrence only

Posted: Mon May 25, 2009 2:34 am
by crishna369
below is my code:

Code: Select all

$val = "(PT) :- PTFE with 316L SST(Diaphragm) 316L SST(Others)";
    $t = preg_replace('/(/', '', $val, 1);
    $tp = preg_replace('/)/', '', $t, 1);
    $temp = str_replace($ans['Code'],"",$tp);
    $temp1 = str_replace(":-","",$temp);
    echo $temp1;
And I m getting this error:
Warning: preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset 1 in C:\xampp\htdocs\crm\replace.php on line 11

Warning: preg_replace() [function.preg-replace]: Compilation failed: unmatched parentheses at offset 0 in C:\xampp\htdocs\crm\replace.php on line 12
():-

Re: how to replace string on first occurrence only

Posted: Tue May 26, 2009 4:36 am
by prometheuzz
mikemike wrote:I'm not convinced your method would be faster you know. I did some benchmarking on the regexp engine and normal replacement not so long ago and it's not that much slower.
On fairly small strings, it doesn't make an awful lot of difference. At least, not noticeable by humans. But, if you're doing a "proper" test on large strings and repeating the tests a number of thousands of times, then you will notice that preg_replace will be much slower than a "simple" string-replace function.

Re: how to replace string on first occurrence only

Posted: Wed Jun 03, 2009 6:21 pm
by mikemike
I appreciate that, but you're not running one function, you're running 3, all for the same result.