猿问

如何在PHP中获得两个字符串之间的子字符串?

如何在PHP中获得两个字符串之间的子字符串?

我需要一个函数来返回两个单词(或两个字符)之间的子字符串。我想知道是否有一个php函数可以实现这一点。我不想考虑regex(嗯,我可以这么做,但实际上并不认为这是最好的方法)。思考strpossubstr职能。下面是一个例子:

$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"}.


犯罪嫌疑人X
浏览 926回答 3
3回答

POPMUISE

正则表达式是要走的路:$str = 'before-str-after';if (preg_match('/before-(.*?)-after/', $str, $match) == 1) {     echo $match[1];}onlinePhp

UYOU

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: ''
随时随地看视频慕课网APP
我要回答