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が上に示しているように、ダッシュの数が混在している文字列があります(1つ、場合によっては2つ)。配列を検索して、すべての単語(およびすべての単語のみ)(ダッシュを除く)が存在するかどうかを確認したいと思います。

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
$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 に答える
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 に答える