如何从第二个或第三个字符串定界符将字符串爆炸回去? [英] How to explode the string back from the second or third string delimiter?
问题描述
如何通过explode()
从此800-555-5555中获得800-555?
How can I get the 800-555 from this 800-555-5555 with explode()
?
这是一个很好的例子:
$rawPhoneNumber = "800-555-5555";
$phoneChunks = explode("-", $rawPhoneNumber);
First chunk = $phoneChunks[0]; //800
Second chunk = $phoneChunks[1]; //555
Third Chunk chunk = $phoneChunks[2]; //5555
但是我如何获得800-555?
But how can I get the 800-555?
好吧,我知道了,这里需要更多注释...所以,这只是一个示例...实际上,我在字符串定界符中添加了一个单词(现在为$ word),并且我的字符串是完整的文章...我想要这个,如果这个词第二次在文章中发布,并以str_word_count()
来计算,那么第二个文本中有多少个字符(或者,如果需要的话,第三个字符)$word
...
Okay, I see, here need more comment... So, this is only an example... In real I add a word (now $word) to string delimiter and my string is a full article... I want that, if this word second time published in the article, with str_word_count()
will count, how many characters was in the text to the second (or third, if I want that) $word
...
因此,我希望从第二个匹配"中获取字符串,并将其返回.
So I want that, I get the string from the second "hit" to back.
好的,这是一个更明显的例子:
Okay, here is a more obvious example:
$text = oh my god, thank you the lot of downvotes, geniuses *.*
$explode = explode(",", $text);
$whatiwant = $explode?? // I WANT THE STRING FROM THE SECOND "," TO BACK
所以我想要$whatiwant = oh my god, thank you the lot of downvotes
推荐答案
Implode
,explode
和array_slice
.
我使用array_slice
是因为这会使函数更加动态.
Implode
, explode
and array_slice
.
I use array_slice
because that makes the function more dynamic.
现在,您只需设置$items
即可获取所需的项目数.
如果设置为负值,则倒计数.
Now you can just set the $items
to get the number of items you want.
If you set a negative value it counts backwards.
$delim = ",";
$items =2;
$text = "oh my god, thank you the lot of downvotes, geniuses *.*";
$whatiwant = implode($delim, array_slice(explode($delim, $text),0,$items));
Echo $whatiwant;
您还可以使用一个起始变量来使起始位置动态化.
You could also have an start variable to make the start position dynamic.
这篇关于如何从第二个或第三个字符串定界符将字符串爆炸回去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!