如何在PHP中获得两个字符串之间的子字符串?我需要一个函数来返回两个单词(或两个字符)之间的子字符串。我想知道是否有一个php函数可以实现这一点。我不想考虑regex(嗯,我可以这么做,但实际上并不认为这是最好的方法)。思考strpos和substr职能。下面是一个例子:$string = "foo I wanna a cake foo";我们称其为函数:$substring = getInnerSubstring($string,"foo"); 回复:“我想要蛋糕”。提前谢谢。最新情况:那么,到现在为止,我只需要在一个字符串中得到两个字以下的子字符串,您允许我再往前走一步,然后问我是否可以扩展getInnerSubstring($str,$delim)要获取在delm值之间的任何字符串,例如:$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"}.
3 回答
![?](http://img1.sycdn.imooc.com/5458643d0001a93c02200220-100-100.jpg)
UYOU
TA贡献1878条经验 获得超4个赞
function getBetween($string, $start = "", $end = ""){ if (strpos($string, $start)) { // required if $start not exist in $string $startCharCount = strpos($string, $start) + strlen($start); $firstSubStr = substr($string, $startCharCount, strlen($string)); $endCharCount = strpos($firstSubStr, $end); if ($endCharCount == 0) { $endCharCount = strlen($firstSubStr); } return substr($firstSubStr, 0, $endCharCount); } else { return ''; }}
echo getBetween("a","c","abc"); // returns: 'b'echo getBetween("h","o","hello"); // returns: 'ell'echo getBetween("a","r","World"); // returns: ''
- 3 回答
- 0 关注
- 925 浏览
添加回答
举报
0/150
提交
取消