Reputation: 787
$string = 'boo-hello--word';
$array = array(
"boo - hello",
"boo - hello world",
"boo - hello world foo",
);
...
foreach ($array as $element) {
if (string_contains_all_words($string, $element) {
// True
$match = $element; // this should be "boo hello world"
}
}
As (hopefully) the php illustrates above, I have a string with a mixed number of dashes (sometimes one, maybe two). I want to search in an array to see if all words (and only ALL words) (excluding the dashes) exists.
Upvotes: 1
Views: 955
Reputation: 91
It's not clear from your question whether the words can be in any order, but I'll assume not. The following code is what I think you're after. :)
<?php
$array = array("boo hello", "boo hello world", "boo hello world foo");
//Removes any dashes (1 or more) from within the string and replaces them with spaces.
$string = trim(preg_replace('/-+/', ' ', $string), '-');
if(in_array($string, $array) {
$match = $string;
} else {
//not match
}
?>
Upvotes: 0
Reputation: 14391
Here's a very simple way of doing it that solves the problem you described.
$string = 'boo-hello--word';
$array = array(
"boo hello",
"boo hello world",
"boo hello word",
"boo hello world foo",
);
$rep_dashes = str_replace('-', ' ', $string);
$cleaned = str_replace(' ', ' ', $rep_dashes);
if (in_array($cleaned, $array)) {
echo 'found!';
}
Upvotes: 3
Reputation: 11566
$string = 'boo-hello--world';
$array = array(
0 => "boo hello",
1 => "boo hello world",
2 => "boo hello world foo",
);
$match = null;
$string = preg_replace('~-+~', ' ', $string);
foreach ($array as $i => $element) {
if ($string == $element) {
// if (preg_match("~^($string)$~", $element)) { // or
$match = $element;
break;
}
}
print $i; // 1
Upvotes: 0