如何在PHP中的两个字符串之间获取子字符串? [英] How to get a substring between two strings in PHP?
问题描述
我需要一个函数,该函数返回两个单词(或两个字符)之间的子字符串.
我想知道是否有实现该功能的php函数.我不想考虑正则表达式(嗯,我可以做一个,但真的不认为这是最好的方法).考虑strpos
和substr
函数.
这是一个例子:
I need a function that returns the substring between two words (or two characters).
I'm wondering whether there is a php function that achieves that. I do not want to think about regex (well, I could do one but really don't think it's the best way to go). Thinking of strpos
and substr
functions.
Here's an example:
$string = "foo I wanna a cake foo";
我们将其称为函数:$substring = getInnerSubstring($string,"foo");
它返回:我想吃蛋糕".
We call the function: $substring = getInnerSubstring($string,"foo");
It returns: " I wanna a cake ".
先谢谢了.
Thanks in advance.
更新:
好吧,到目前为止,我只能在一个字符串中得到两个单词之间的一个子字符串,您允许我走得更远一点,问我是否可以扩展使用getInnerSubstring($str,$delim)
来获取介于delim值之间的任何字符串. ,例如:
Update:
Well, till now, I can just get a substring beteen two words in just one string, do you permit to let me go a bit farther and ask if I can extend the use of getInnerSubstring($str,$delim)
to get any strings that are between delim value, example:
$string =" foo I like php foo, but foo I also like asp foo, foo I feel hero foo";
我得到一个像{"I like php", "I also like asp", "I feel hero"}
的数组.
推荐答案
If the strings are different (ie: [foo] & [/foo]), take a look at this post from Justin Cook. I copy his code below:
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
这篇关于如何在PHP中的两个字符串之间获取子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!