[SOLVED] Replace only one instance

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Archy
Forum Contributor
Posts: 129
Joined: Fri Jun 18, 2004 2:25 pm
Location: USA

[SOLVED] Replace only one instance

Post 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.
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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;
?>
User avatar
wwwapu
Forum Contributor
Posts: 197
Joined: Wed Apr 07, 2004 11:57 am
Location: Turku, Finland

Post 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...
Archy
Forum Contributor
Posts: 129
Joined: Fri Jun 18, 2004 2:25 pm
Location: USA

Post 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.
Post Reply