Jump to content

string difference


cody7

Recommended Posts

Hi Gurus

 

Please help me figure this out

 

$filter = array("just","very short", "long", "two words", "other"); // this list is about 400 array content
$str1 = "This is just a sample text, a very short one";
$str2 = str_replace($filter, "", $str1);

 

So when I echo $str2

 

"This is  a sample text, a  one"

 

My Question is. what is the best way to know what word(s) from $filter is present in $str1, since str_replace will only return the changed value. for this example ("just","very short") are the words I want to store in an array

 

Array
(
    [0] => just
    [1] => very short
)

 

 

Please note that I am only using PHP4.

Feel free to change the technique if you have other method of extracting the words given above.

 

Thank you for all your help

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/163885-string-difference/
Share on other sites

I don't think it's possible to do that with str_replace. To get the variables that will be replaced you can make a simple function like this:

 

function replacedWords($string, $filter)
{
foreach($filter as $word)
{
	 if(stripos($string, $word) === false){}else
	 {
		$replaced[] = $word;
	 }
}
return $replaced;
}
$filter = array("just","very short", "long", "two words", "other");
$str1 = "This is just a sample text, a very short one";
$replaced = replacedWords($str1, $filter);
$str2 = str_replace($filter, "", $str1); 

print_r($replaced);// Array ( [0] => just [1] => very short )

Link to comment
https://forums.phpfreaks.com/topic/163885-string-difference/#findComment-864677
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.