I am looping through an associative array and trying to match the whole word from the needle array into the haystack array. The following code works perfectly but returns too many results since it's matching any occurance of the string:
$result = array();
$name1 = array();
$name2 = array();
foreach($object->organizations as $o) {
foreach($objectCrunch as $o2) {
$name1 = $o->name;
$name2 = $o2->name;
if(stristr($name2, $name1)) {
$result[] = $o2->permalink;
}
}
}
When I try the following code:
$result = array();
$name1 = array();
$name2 = array();
foreach($object->organizations as $o) {
foreach($objectCrunch as $o2) {
$name1 = $o->name;
$name2 = $o2->name;
$pattern = "'/\b" . $name2 . "\b/i'";
if(preg_match($pattern, $name1)) {
$result[] = $o2->permalink;
}
}
}
I get an empty array. Any help getting the last piece of code working would be great.
Thanks, Greg
You are using two pairs of delimiters here:
$pattern = "'/\b" . $name2 . "\b/i'";
||
1|
2
Use either /
or '
.
I'd say the single quotes are redundant and the result of hasty copy & pasting.
Also, preg_quote
for the content/word if it might contain either.
So as Elias points out; The next pitfall is likely trying to use the long content variable as search parameter. This would have been an obvious error, if you didn't give your variables meaningless enumerated names.
Only one of them is likely an actual word or name. The other should be called content or something:
$word = $o->name;
$textcontent = $o2->name;
Use those henceforth.
While at it, also fix the object property naming accordingly.
It's perfectly simple, really. Thanks to some quirks in php, stristr
syntax is as follows:
stristr($haystack,$needle);
while preg_match
's first argument serves as a needle. Example:
$name1 = 'name of chief object';
$name2 = 'I am a child of name of chief object';
stristr($name2,$name1);//looks for 'name of chief object' in $name2
preg_match('/\b'.$name2.'\b/i',$name1);//does the exact oposite