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);
1
  • you can use preg_match("/@username(?=\\s|$)/", $username) Commented May 29, 2016 at 16:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

\b may be wrong here because it will match @username+xyz which may not be what OP wants
@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 :)
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.

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.