开发者

Check if any array values are present at the end of a string

开发者 https://www.devze.com 2023-03-11 09:19 出处:网络
I am trying to test if a string made up of multiple words and has any values from an array at the end of it. The following is what I have so far. I am stuck on how to check if the string is longer tha

I am trying to test if a string made up of multiple words and has any values from an array at the end of it. The following is what I have so far. I am stuck on how to check if the string is longer than the array value being tested and that it is present at the end of the string.

$words = trim(preg_replace('/\s+/',' ', $string));
$words = exp开发者_Go百科lode(' ', $words);
$words = count($words);

if ($words > 2) {
    // Check if $string ends with any of the following
    $test_array = array();
    $test_array[0] = 'Wizard';
    $test_array[1] = 'Wizard?';
    $test_array[2] = '/Wizard';
    $test_array[4] = '/Wizard?';

    // Stuck here
    if ($string is longer than $test_array and $test_array is found at the end of the string) {
      Do stuff;
    }
}


By end of string do you mean the very last word? You could use preg_match

preg_match('~/?Wizard\??$~', $string, $matches);
echo "<pre>".print_r($matches, true)."</pre>";


I think you want something like this:

if (preg_match('/\/?Wizard\??$/', $string)) { // ...

If it has to be an arbitrary array (and not the one containing the 'wizard' strings you provided in your question), you could construct the regex dynamically:

$words = array('wizard', 'test');
foreach ($words as &$word) {
    $word = preg_quote($word, '/');
}
$regex = '/(' . implode('|', $words) . ')$/';
if (preg_match($regex, $string)) { // ends with 'wizard' or 'test'


Is this what you want (no guarantee for correctness, couldn't test)?

foreach( $test_array as $testString ) {
  $searchLength = strlen( $testString );
  $sourceLength = strlen( $string );

  if( $sourceLength <= $searchLength && substr( $string, $sourceLength - $searchLength ) == $testString ) {
    // ...
  }
}

I wonder if some regular expression wouldn't make more sense here.

0

精彩评论

暂无评论...
验证码 换一张
取 消