查找字符串数组的位置首次出现在一个字符串 [英] Find position first occurence of an array of strings in a string

查看:1022
本文介绍了查找字符串数组的位置首次出现在一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP有一个函数 strpos()查找字符串中的给定值的第一个实例的位置。有没有办法用针是一个字符串数组做到这一点?它会给第一次出现:

  $海峡='1和第3';str_array_pos($ str中,阵列('ST','次','次','日'))//将返回因为ST1


解决方案

您可以写一个自己:

 函数str_array_pos($字符串,$阵列){
  为($ i = 0,$ N =计数($数组); $ I< $ N; $ I ++)
    如果(($ POS = strpos($字符串,$数组[$ i]))!= = FALSE)
      返回$ POS;
  返回false;
}

顺便说一句,在你的例子中,返回值应该是0,而不是1,因为数组的下标从0开始。

PHP has a function strpos() for finding the position of the first instance of a given value in a string. Is there a way to do this with a needle that is an array of strings? It would give the first occurence:

$str = '1st and 3rd';

str_array_pos($str, array('st', 'nd', 'rd', 'th')) //would return 1 because of 'st'

解决方案

You could write one yourself:

function str_array_pos($string, $array) {
  for ($i = 0, $n = count($array); $i < $n; $i++)
    if (($pos = strpos($string, $array[$i])) !== false)
      return $pos;
  return false;
}

By the way, the return value in your example should be 0 and not 1 since array indices start at 0.

这篇关于查找字符串数组的位置首次出现在一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆