Page 1 of 1

[SOLVED] Replace only one instance

Posted: Fri Feb 18, 2005 4:31 pm
by Archy
Is there a way to only replace 1 instance of a string within a string. For instance:

$string = "The house is made of bricks bricks.";

Is there a way to only take out the first "bricks" within that string. Please bare in mind that the string could be anything, of any length.

Thanks.

Posted: Fri Feb 18, 2005 4:42 pm
by markl999

Code: Select all

<?php
$replacement = 'bricks';
$string = 'The house is made of bricks bricks.';
$string = substr_replace($string, '', strpos($string, $replacement), strlen($replacement));
echo $string;
?>

Posted: Fri Feb 18, 2005 4:46 pm
by wwwapu
You could explode() your string and compare each "substring" against the next. If they are not the same then add the compared one to your output string. Something like

Code: Select all

function removeSame($jono)&#123;
  jonoArray=explode($jono);
  $outPutString=""
  for($i=0; $i<count($jonoArray)-1;$i++)&#123;
    if($jonoArray&#1111;$i] != $jonoArray&#1111;$i+1])&#123;
    $outPutString .=$jonoArray&#1111;$i] . " ";
  &#125;
  return $outPutString;
&#125;
But this could be very time and resorces consuming. Even useless...

Posted: Fri Feb 18, 2005 4:50 pm
by Archy
Thanks markl999, worked well.
Thanks for trying to help wwwapu, although as you said, it would be more resource demanding.

" substr_replace -- Replace text within a portion of a string "

Brain didnt register that "portion of a string" bit. : )
Thanks.