PHP - Searching for a Set of Characters with strpbrk()

Introduction

To find out if a string contains any one of a set of characters, use strpbrk() function.

It takes two arguments:

  • the string to search, and
  • a string containing the list of characters to search for.

The function returns the portion of the string from the first matched character to the end of the string.

If none of the characters in the set are found in the string, strpbrk() returns false.

Demo

<?php
$myString = "Hello, world!";
echo strpbrk( $myString, "abcdef" ); // Displays'ello, world!'
echo strpbrk( $myString, "xyz" ); // Displays''(false)

$username = "matt@example.com";
if ( strpbrk( $username, "@!" ) ) echo "@ and ! are not allowed in usernames";
?>/*from w  w w.  j  av a  2s .  c  o m*/

Result

Related Topic