我有一个PHP字符串,例如这个字符串(haystack):
$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中实现吗?
这类似于question,但这适用于JavaScript。
答案 0 :(得分: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 ;
}
}
答案 1 :(得分: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);
?>
答案 2 :(得分: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
模式\:|\,|\||\)
答案 3 :(得分: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);
您可以see it working - 阅读strpbrk
strpbrk
返回第一个匹配字符后的字符串
$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 :)";
$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 :)";
依此类推,直至不匹配
$string = ")";
// strpbrk doesn't match and return false
$match = false;
// We get out of the while