使用多个定界符将文本拆分为修剪后的值的数组 [英] Split text using multiple delimiters into an array of trimmed values
问题描述
我有一组字符串,需要将它们分块成一个数组.字符串需要在/
,,
, with
或&
上拆分.
I've got a group of strings which I need to chunk into an array.
The string needs to be split on either /
, ,
, with
, or &
.
不幸的是,一个字符串可能包含两个需要分割的字符串,所以我不能使用 split()
或 explode()
Unfortunately it is possible for a string to contain two of the strings which needs to be split on, so I can't use split()
or explode()
.
例如,字符串可以说第一个过去/超出&然后打开
,所以我试图获取一个将返回的数组:
For example, a string could say first past/ going beyond & then turn
, so I am trying to get an array that would return:
array('first past', 'going beyond', 'then turn')
我当前使用的代码是
$splittersArray=array('/', ',', ' with ','&');
foreach($splittersArray as $splitter){
if(strpos($string, $splitter)){
$splitString = split($splitter, $string);
foreach($splitString as $split){
我似乎找不到在PHP中允许我执行此操作的函数.我是否需要将字符串传递回漏斗的顶部,并在一次又一次地拆分字符串之后继续通过 foreach()
?
I can't seem to find a function in PHP that allows me to do this.
Do I need to be passing the string back into the top of the funnel, and continue to go through the foreach()
after the string has been split again and again?
这似乎不是很有效.
推荐答案
使用正则表达式,并 preg_split .
在您提到的情况下,您将获得带有以下内容的拆分数组:
In the case you mention, you would get the split array with:
$splitString = preg_split('/(\/|\,| with |\&/)/', $string);
这篇关于使用多个定界符将文本拆分为修剪后的值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!