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"
   }
}

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.

8
  • 1
    Split by dashes+, sort, compare.
    – raina77ow
    Commented Jan 30, 2013 at 17:08
  • you can also use in_array()
    – Drewdin
    Commented Jan 30, 2013 at 17:09
  • I've looked at preg_match but I couldn't figure out the pattern. Could you show an example please?
    – Nadine
    Commented Jan 30, 2013 at 17:09
  • why not "boo hello world foo" too? it contains the string. If I understood the opposite than "boo hello" or do u mean a 100% match when remove all none word characters? Commented Jan 30, 2013 at 17:10
  • I need a 100% match. For my case, setting $match with "boo hello world foo" would be wrong.
    – Nadine
    Commented Jan 30, 2013 at 17:12

3 Answers 3

3

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!';
}
3
  • This is the exact same solution I was going to give. simple and easy +1
    – Drewdin
    Commented Jan 30, 2013 at 17:24
  • Nice solution. However, what about if array also contains dashes? I've just updated my question to include this
    – Nadine
    Commented Jan 30, 2013 at 17:59
  • 2
    modify the above to account for the change. str_replace('-', ' - ', string) str_replace('--', ' ', $rep_dashes)
    – Drewdin
    Commented Jan 30, 2013 at 18:02
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
0

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
    }
?>

Not the answer you're looking for? Browse other questions tagged or ask your own question.