4

我有一个 PHP 字符串,例如这个字符串(干草堆):

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";

现在我想按照针在字符串中出现的顺序设置一个 PHP 数组。所以这是我的针:

$needle = array(",",".","|",":");

$text字符串中搜索针时,这应该是输出:

Array (
   [0] => :
   [1] => ,
   [2] => .
   [3] => |
   [4] => :
)

这可以在PHP中实现吗?

这与这个问题类似,但这是针对 JavaScript 的。

4

4 回答 4

1

str_split在这里可能很方便

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$needles = array(",",".","|",":");
$chars = str_split($string);

$found = array();

foreach($chars as $char){
  if (in_array($char, $needles)){
    $found[] = $char ;
  }
}
于 2013-09-11T14:07:07.207 回答
0

这将为您提供预期的结果:

     <?php
    $haystack= "here is a sample: this text, and this will be exploded. this also | this one too :)";
    $needles = array(",",".","|",":");
    $result=array();
    $len = strlen($haystack) ;
    for($i=0;$i<$len;$i++) {
        if(in_array($haystack[$i],$needles)) {
            $result[]=$haystack[$i];
        }
    }
    var_dump($result);
?>
于 2013-09-11T14:11:37.197 回答
0
$string = "here is a sample: this text, and this will be exploded. th
is also | this one too :)";

preg_match_all('/\:|\,|\||\)/i', $string, $result); 

print_r(  array_shift($result) );

利用preg_match_all

图案\:|\,|\||\)

工作演示...

于 2013-09-11T14:11:48.047 回答
0

好吧,让我们只是为了好玩

$string = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$needle = array(",",".","|",":");
$chars  = implode($needle);
$list   = array();

while (false !== $match = strpbrk($string, $chars)) {
    $list[] = $match[0];
    $string = substr($match, 1);
}

var_dump($list);

你可以看到它工作- 阅读strpbrk

解释

strpbrk返回第一个匹配字符之后的字符串

转弯 1

$string = "here is a sample: this text, and this will be exploded. this also | this one too :)";

// strpbrk matches ":"
$match = ": this text, and this will be exploded. this also | this one too :)";

// Then, we push the first character to the list ":"
$list = array(':');

// Then we substract the first character from the string
$string = " this text, and this will be exploded. this also | this one too :)";

转 2

$string = " this text, and this will be exploded. this also | this one too :)";

// strpbrk matches ","
$match = ", and this will be exploded. this also | this one too :)";

// Then, we push the first character to the list ","
$list = array(':', ',');

// Then we substract the first character from the string
$string = " and this will be exploded. this also | this one too :)";

以此类推,直到没有匹配

转 5

$string = ")";

// strpbrk doesn't match and return false
$match = false;

// We get out of the while
于 2013-09-11T14:11:58.523 回答