1

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 = explode(' ', $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;
    }
}

3 Answers 3

2

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>";
Sign up to request clarification or add additional context in comments.

1 Comment

This works great! I added ignore case, but this is simple and gets the job done. if (preg_match('~/?Wizard\??$~i', $string)) {
2

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'

1 Comment

Thanks for this, the second part in regards to arbitrary arrays will be helpful for something I need to do in the near future.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.