Randomly select a word from array

jimbbob

Newbie
Joined
Oct 2, 2012
Messages
10
Reaction score
0
I want to replace a word with its synonyms but I don't it to replace the word with the original word. (Like a spinner)

This is the code that Zak_A from the forum helped me with:
PHP:
<?php
 
$text = 'Honda is a truck.';

$array1 = array( 'sedan', 'coupe', 'truck' );
$replace1 = "{sedan|coupe|truck}";

$array2 = array('Honda','Toyota','Nissan');
$replace2 = "{Honda|Toyota|Nissan}";

$tmp = str_replace($array1,'##1',$text);
$tmp = str_replace($array2,'##2',$tmp);

$result = str_replace('##1',$replace1,$tmp);
$result = str_replace('##2',$replace2,$result);

echo $result;

?>


For example if I write:

Honda is a sedan.

My replacement words for "Honda" are "Honda,Toyota,Nissan" so after the script runs, is it possible for it to select one of those words and output for example: Nissan is a seddan or Toyota is a sedan. Even though "Honda" is part of the list, it should skip that option since its that was found in the original text. Can someone please help me with this. Thank you!
 
Last edited:
You can use in_array() function to check if the word you got is present in the array. If it's present ignore that and fetch the next value which won't be the same.
 
sorry i forgot to mention, I'm understand a little bit of PHP but I'm not able to put together my own code that well.
 
I have been testing around and have updated the code so that it randomly selects from the array. But at the moment, it does not exclude the original word as in the "Honda"
 
Try this. I added code at the bottom for replacement of Honda. You can set this up for replacement of any of the words using the same technique. You need to set the keyword you're trying to avoid, then pull a random value from the array. If it matches ignore, otherwise do a string replacement they way I've shown. I just tested this so it should work. Let me know if it doesn't.

Code:
 <?php
 
$text = 'Honda is a truck.';

$array1 = array( 'sedan', 'coupe', 'truck' );
$replace1 = "{sedan|coupe|truck}";

$array2 = array('Honda','Toyota','Nissan');
$replace2 = "{Honda|Toyota|Nissan}";

$tmp = str_replace($array1,'##1',$text);
$tmp = str_replace($array2,'##2',$tmp);

$result = str_replace('##1',$replace1,$tmp);
$result = str_replace('##2',$replace2,$result);

echo $result;


$keyword = 'Honda';
$newkeyword = $array2[array_rand($array2)];

if($keyword == $newkeyword) {
	// you matched the existing keyword so you don't want to do anything
}else{	
	$result=str_replace($keyword,$newkeyword,$text);
}
?>
 
Last edited:
Back
Top