Home > Enterprise >  How to find array value on a string?
How to find array value on a string?

Time:03-20

i have a string like this

// this string contain "Example!"
$string1 = "Example! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tortor ipsum, faucibus iaculis dapibus ut, mollis vel diam.";

and array with string that i need to search

$array_to_find = [
    "#Example",
    "Example!",
    "Example?"
];

how can i find any string inside $array_to_find on $string1? like

if( ... ){ //if $array_to_find was found on the $string1 
  $matched_value = ""; // set $matched_value as the string that was found (for this "Example!" found on $string1)
  
  // do something after
}

CodePudding user response:

You can use str_contains on php 8.0 to search in text

See an example:

$string1 = "Example! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tortor ipsum, faucibus iaculis dapibus ut, mollis vel diam.";
$array_to_find = [
    "#Example",
    "Example!",
    "Example?"
];


$matches = array_filter($array_to_find, static fn ($textToFind) => str_contains($string1, $textToFind) );


var_dump($matches);

CodePudding user response:

/**
 * This function only assumes that $haystack does not contain the character '|'
 */
function get_found_strings(string $haystack, array $needles): array
{
    $regex = '/' . str_replace('\|', '|', preg_quote(implode('|', $needles))) . '/';

    preg_match_all($regex, $haystack, $matches);
    return $matches[0];
}
$string1 = "Example! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tortor ipsum, faucibus iaculis dapibus ut, mollis vel diam.";

$array_to_find = [
    "#Example",
    "Example!",
    "Example?"
]; // REGEX = /\#Example|Example\!|Example\?/

var_dump(get_found_strings($string1, $array_to_find));

Code demo: https://3v4l.org/WtUVM#v8.1.4

Regex test: https://www.phpliveregex.com/p/E4t

  • Related