1
$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 所示,我有一个包含多个破折号的字符串(有时是一个,也许是两个)。我想在一个数组中搜索以查看是否所有单词(并且只有所有单词)(不包括破折号)都存在。

4

3 回答 3

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!';
}
于 2013-01-30T17:17:50.503 回答
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
    }
?>
于 2013-01-30T17:19:30.440 回答
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
于 2013-01-30T17:16:25.467 回答