1

I'm trying to validate my input in PHP, how to check if @username exists in the string in the following valid formats in UTF8?

Valid:

  • "Hello @username"
  • "Hello@username"
  • "Hello @username how are you?"

Invalid

  • "Hello username"
  • "Hello @usernamehow are you?"

The following code works, but claims "@usernamehow" is valid when searching for "@username"

$userMentioned = substr_count($text, $username);
Khalid Al-Mutawa
  • 829
  • 1
  • 9
  • 16

2 Answers2

1

I think you're basically asking how to check if a word is present within a string with PHP. This could be done by using REGEX as rock321987 suggested, or by using strpos():

$word = " @username ";
$string = "Hello @username how are you?";

if (strpos($string, $word) !== false) {
    die('Found it');
}

I found out that Laravel is using the exact same approach:

/**
 * Determine if a given string contains a given substring.
 *
 * @param  string  $haystack
 * @param  string|array  $needles
 * @return bool
 */
function str_contains($haystack, $needles)
{
    foreach ((array) $needles as $needle)
    {
        if ($needle != '' && strpos($haystack, $needle) !== false) return true;
    }
    return false;
}

Hope this helps.

Community
  • 1
  • 1
JasonK
  • 5,214
  • 9
  • 33
  • 61
1

To match the specific patterns you mention, you could use a simple Regular Expression with a one-sided word boundary:

$pattern = '/@username\b/';
$userMentioned = preg_match($pattern, $testString);

That will ensure there is no other letters or numbers on the right side, but allows for it on the left side.

Atli
  • 7,855
  • 2
  • 30
  • 43
  • `\b` _may_ be wrong here because it will match `@username+xyz` which _may_ not be what OP wants – rock321987 May 29 '16 at 16:36
  • @rock321987 I can't speak to that, but it will definitely work for the data he presented. I can see use-cases both for allow it and not. - Best not to over-engineer the solution unless we know one way or the other. "KISS", and all that :) – Atli May 29 '16 at 16:49