$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"
}
}
正如(希望)php在上面说明的那样,我有一个混合数字的破折号(有时一个,也许两个)。我想在一个数组中搜索,看看是否所有单词(只有所有单词)(不包括破折号)都存在。
答案 0 :(得分:3)
这是一种非常简单的方法,可以解决您描述的问题。
$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!';
}
答案 1 :(得分:0)
$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
答案 2 :(得分:0)
从你的问题不清楚这些词是否可以按任何顺序排列,但我不会假设。以下代码是我认为你想要的。 :)
<?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
}
?>