php - 找到正确的出现顺序

标签 php

我有一个 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 的。

最佳答案

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 ;
  }
}

关于php - 找到正确的出现顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18743373/

相关文章:

php - 抑制生产服务器上的 php 错误的最佳方法

php - 将表从一个数据库复制到另一个数据库但使用不同的用户,joomla 中的 php

php - 将数据从 php 回显到 ajax 并打印

php - 获取在 Laravel 3/4 中执行的查询

php - 基于时区的碳上两次以秒为单位的差异

php - 在 Moodle 3.5 中添加新用户时出错

java - 如何使用 SOAP 将对象从 PHP 发送到 Java Web 服务?

php - 棘手的 MySQL 搜索

php - 如何使用异步脚本获取 tail -f 结果?

php - 使用 PHPExcel 从 MySQL 获取字段名称到 Excel