2010-08-26 43 views
1

如何根據php中的字符串內容返回部分字符串。不像在您使用的整數長度基於字符串的返回字符串段

所以,如果我們得到這樣 here is a nice string that is being used as an example

串SUBSTR()和相關職能,我們怎麼能回到這樣

nice string

不知何故字符串我們必須通過功能athat,以便知道起點和終點。它會找到第一個a,然後開始跟蹤字符,然後當它發現that它將停止並返回。

要清楚:我們知道原始字符串的內容......以及發送的參數。

回答

2

使用此功能:

function get_string_between($string, $start, $end) 
{ 
    $ini = strpos($string,$start); 
    if ($ini == 0) 
     return ""; 
    $ini += strlen($start); 
    $len = strpos($string,$end,$ini) - $ini; 
    return substr($string,$ini,$len); 
} 

$input = 'here is a nice string that is being used as an example'; 
$output = get_string_between($input, 'a', 'that'); 
echo $output; //outputs: nice string 
+0

此打印 '好串',但它是它應該是什麼?返回字符串應該是'nice string' - 沒有空格。 – vtorhonen 2010-08-26 10:35:33

+0

@vtorhonen,爲此,你可以使用'get_string_between($ input,'a','that');' – shamittomar 2010-08-26 11:18:08

2

你可以使用正則表達式也有preg_match

<?php 

function get_string_between($string,$start,$end) { 
    preg_match("/\b$start\b\s(.*?)\s\b$end\b/",$string,$matches); 
    return $matches[1]; 
} 

$str = "here is a nice string that is being used as an example"; 
print get_string_between($str,"a","that")."\n"; 

?>