str_replace & concatenate

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
kirk7880
Forum Newbie
Posts: 3
Joined: Wed Feb 08, 2006 3:32 pm

str_replace & concatenate

Post by kirk7880 »

How do you replace a string and then concatenate additional information?


The code below performs the string replace. I just need to know how to concatenate info the the replaced string

$buffer = str_replace('"/wiki/', '"' . $pathfromroot . '/spelling/query_term-', $buffer);
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

PLEASE USE PHP TAGS AND PHP BBCODE.

Replacing a string:

Code: Select all

<?php
$old_string = 'ThisOldThing';
$new_string = 'BrightShinyThing';
$container = 'IHaveThisOldThing';

//Make a nicer sentence
$container = str_replace($old_string, $new_string, $container);
echo $container;

// This outputs 'IHaveBrightShinyThing'
?>
Concatenating is done like this:

Code: Select all

<?php
$old_string = 'ThisOldThing';
$new_string = 'BrightShinyThing';

$new_string = $old_string . ' stinks compared to ' . $new_string;
echo $new_string;

//This outputs 'ThisOldThing stinks compared to BrightShinyThing'
?>
In your example you should be able to concatenate anywhere near the str_replace call:

Code: Select all

<?php
$buffer = 'ConcatBefore' . str_replace('"/wiki/', '"' . $pathfromroot . '/spelling/query_term-', $buffer) . 'ConcatAfter';
?>
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

I think the OP wanted to concatentate onto the result, but all in one statement....

Code: Select all

$buffer = preg_replace('/(.*?)wiki(.*)/', '$1$2'.$pathfromroot.'/spelling/query_term-', $buffer);
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Yeah, I wasn't sure so I started with the easiest idea first. Thanks for following up.
Post Reply