字符串函数
在线手册:中文 英文
PHP手册

strpbrk

(PHP 5)

strpbrk在字符串中查找一组字符的任何一个字符

说明

string strpbrk ( string $haystack , string $char_list )

strpbrk() 函数在 haystack 字符串中查找 char_list 中的字符。

参数

haystack

在此字符串中查找 char_list

char_list

该参数区分大小写。

返回值

返回一个以找到的字符开始的子字符串。如果没有找到,则返回 FALSE

范例

Example #1 strpbrk() 范例

<?php

$text 
'This is a Simple text.';

// 输出 "is is a Simple text.",因为 'i' 先被匹配
echo strpbrk($text'mi');

// 输出 "Simple text.",因为字符区分大小写
echo strpbrk($text'S');
?>

参见


字符串函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 在字符串中查找一组字符的任何一个字符

用户评论:

b dot pleshka at gmail dot com (04-Jan-2012 08:55)

Simple code to define symbol (@) in the string

<?php
$name
= "username@example.com";
if (
strpbrk($name, '@') != FALSE) {
    echo
"There is @";
}
else {
    echo
"There isn't @";
}
?>

root at mantoru dot de (07-Feb-2008 03:55)

A simpler (and slightly faster) strpbrkpos function:

<?php
function strpbrkpos($haystack, $char_list) {
   
$result = strcspn($haystack, $char_list);
    if (
$result != strlen($haystack)) {
        return
$result;
    }
    return
false;
}
?>

pzb at novell dot com (29-Jul-2007 12:09)

One undocumented requirement:
If $char_list contains null characters ("\0"), only characters before the null will be used.  While PHP handles nulls in strings just fine, the data is passed to a function that is not null safe.

Evan (04-Jul-2007 04:33)

If you're not looking to duplicate the rest of the string, but instead just want the offset, in the spirit of the str*pos() functions:

<?php

function strpbrkpos($s, $accept) {
 
$r = FALSE;
 
$t = 0;
 
$i = 0;
 
$accept_l = strlen($accept);

  for ( ;
$i < $accept_l ; $i++ )
    if ( (
$t = strpos($s, $accept{$i})) !== FALSE )
      if ( (
$r === FALSE) || ($t < $r) )
       
$r = $t;

  return
$v;
}

?>

user at example dot net (03-Jul-2007 08:25)

For PHP versions before 5:

<?php

   
function strpbrk( $haystack, $char_list )
    {
       
$strlen = strlen($char_list);
       
$found = false;
        for(
$i=0; $i<$strlen; $i++ ) {
            if( (
$tmp = strpos($haystack, $char_list{$i})) !== false ) {
                if( !
$found ) {
                   
$pos = $tmp;
                   
$found = true;
                    continue;
                }
               
$pos = min($pos, $tmp);
            }
        }
        if( !
$found ) {
            return
false;
        }
        return
substr($haystack, $pos);
    }

?>

Sadly this is about ten times slower than the native implementation.

jamie dot mcardle at stpetersgv dot org (07-Jun-2007 10:54)

I wanted to use this function to look for an @ in a db entry - didn't work because I don't have this version of PHP yet, but I thought I had my issue licked. Darn it.

aidan at php dot net (21-Aug-2004 09:11)

This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat