Need some PHP guidance

Soldato
Joined
4 Jul 2004
Posts
2,647
Location
aberdeen
Hello,
I am not asking people to do this for me, just send me in the right direction.

Basically i have a string ($mywords), and another string ($wordtoreplace).
$wordtoreplace is set up like:

word1|word2
word3|word4

basically i want it so it'll go through each word within $mywords (as mywords could be something like "example example2 another word word1"), and see if it can find that word on a line in $wordtoreplace. If it does, which using these examples, it would only find word1 on it, it then replaces word1 with the other word on that line, ie word2.

How can i search through a load of text to see if a certain word is in it, and if it is, how can i find what line that word is on within the string?

thanks
 
How do you want $wordstoreplace to work?

Is there anyway you could turn that $wordstoreplace into a 3d array?

eg.

word1|word2
word3|word4

would become

$replacements['1']['oldword'] = word1
$replacements['1']['newword'] = word2
$replacements['2']['oldword'] = word3
$replacements['2']['newword'] = word4

Then you could use the function

http://uk2.php.net/str_replace

Hope this helps!
 
Try this

Be Warned: This is my logic at 2am :D

PHP:
$wordtoreplace = 'word1|word2
word3|word4';

$mywords = 'word1 and word2!';

$wordtoreplace_array1 = explode("\n", $wordtoreplace);

foreach($wordtoreplace_array1 as $wordtoreplace_value {
	$replace_words = explode('|', $wordtoreplace_value);
		if (str_pos($mywords, $replace_words[0]) !== FALSE) {
			$mywords = str_replace($replace_words[0], $replace_words[1], $mywords);
		}
}

AND I didnt test it :)
 
Last edited:
i'd do it with an associative array like this.....

PHP:
$array = array('original_word1' => 'replacement_word1',
'original_word2' => 'replacement_word2');

$string = 'original_word1 original_word2';

foreach($array as $original => $replace) {
    $string = str_replace($original, $replace, $string);
}

:)
 
Hi
Ok thanks, i'll play with those. I idealy wanted to be able to have something more like
word1|word2|word3|etc
rather than just word1 and word2 on each line though.
 
str_replace can accept arrays for both the needles and the replacements. It will also only replace the needle with the replacement of the same index.

PHP:
 $array = array('original_word1' => 'replacement_word1',
'original_word2' => 'replacement_word2');

$string = 'original_word1 original_word2'; 

$new_string = str_replace(array_keys($array), $array, $string);
 
Back
Top Bottom