2011-01-31 137 views
0

我想學習正則表達式,並有一個字符串一些正則表達式,我要開始爲(不包括)PHP沒有結束

.com/ 

,並最終成爲(不包括)

">[tomato 

我可以使基本的正則表達式正常,但它保持包括番茄部分,而不是在它之前結束。所以,如果我有

'sdf98uj3.com/sdjkh.sdf./sdf.sdf">[tomatoiosdf8uj3' 

,那麼我想返回:

sdjkh.sdf./sdf.sdf 

我在PHP中使用的preg_match。有任何想法嗎?

+0

如果你實際上是在解析URL或HTML (儘管它們對很多事情都非常漂亮,值得學習)。對於URL,請查看parse_url或pathinfo下的PHP手冊。對於HTML,看看SimpleXML。 – dnagirl 2011-01-31 17:30:47

回答

1
preg_match('~\.com/(.*?)">\[tomato~', $str, $match); 

$match[1]包含您的字符串。 (.*?)是一個capture group,它捕獲.com/">[tomato之間的每個字符。

http://www.regular-expressions.info/是學習正則表達式的好開始。


也沒有正則表達式來解決,使用strpos(docs)strrpos(docs)substr(docs):,正則表達式是不是最好的方式去

$start = strpos($str, '.com/'); 
$end = strrpos($str, '">[tomato'); // or strpos to find the first occurance 
$sub = substr($str, $start, $end-$start); 
+0

我知道他們會是一個更好的方式!謝謝! – David19801 2011-01-31 17:28:10

0
preg_match('/(.*?)\.com/(.*?)">\[tomato(.*)/', $text, $matches); 

echo $matches[2];