2015-03-25 26 views
-1

我想要檢測主字符串中子字符串的出現,但子字符串可以從空格開始或(在開始或結束括號結束時)。在結束點從php字符串開始檢測空格或括號從字符串開始php

我想寫一個正則表達式,其中檢測到所有4條件,並計算php 發生編輯 - 感謝JE SUIS我可以檢查開始和結束條件,但它只適用於$ mainspring =「PHP 「這不適用於」這是php「。 它不會忽略php之前的單詞。

有沒有什麼辦法可以在比賽之前和比賽之後忽略所有的字符串?

$mainString = "i love java but i want to learn php and this keyword ofphp should not be count because there is no space before php but this could be count (php)"; 
    $keyword = "php"; 
    $match =preg_match('/^[(\s]?'.$keywords.'[.)]?$/', $mainString); 
    var_dump($match); 

我不知道我怎麼能寫的正則表達式這個條件 任何幫助,將不勝感激

謝謝

+1

'$ match = preg_match('/^\($ keyword \)/',$ mainString);'將匹配圓括號內的'$ keyword'。您可以進一步處理這些內容以添加更多條件作爲字符類。 – 2015-03-25 08:43:44

回答

1

這將做的工作:

preg_match('/^[(\s]$keyword[.)]$/', $mainString, $match); 

其中:

/   : regex delimiter 
^  : begin of string 
    [(\s]  : an open parenthesis or a space 
    $keyword : the keyword to find 
    [.)]  : a dot or a close parenthesis 
    $   : end of string 
/   : regex delimiter 

請注意,preg_match的結果是一個布爾值,匹配在第三個參數中。

根據編輯評論:

如果你想在字符串中間匹配$keyword,只是刪除錨點^$

preg_match('/[(\s]$keyword[.)]/', $mainString, $match); 

如果你之前的一些十六進制字符和之後:

preg_match('/[0-9a-fA-F][(\s]$keyword[.)][0-9a-fA-F]/', $mainString, $match); 

如果th ey不是強制性的:

preg_match('/[0-9a-fA-F]?[(\s]$keyword[.)][0-9a-fA-F]?/', $mainString, $match); 
+0

SUIS謝謝你的幫助..但我想添加一個東西到它之前「$關鍵字之前可能有另一個文本或關鍵字後,所以我可以改變正則表達式這樣的事情」[0-9a-fA-F]/^ [(\ s] $關鍵字[。]] $/[0-9a-fA-F]「 因爲你的正則表達式工作時,我只是把單個關鍵字放入MainString ... etêtes-vousfrançais? – 2015-03-25 10:49:15

+0

@ Swap-IOS -Android:查看我的編輯 – Toto 2015-03-25 12:36:35

+0

Suis非常感謝您的好解釋 – 2015-03-25 13:04:30

相關問題