2017-04-22 177 views
-3

我有以下的字符串下面將其通過DOM Document萃取:Validade如果字符串包含一個正則表達式串

$scripts = $doc->getElementsByTagName('script'); 
$script = $scripts->item($i); 
$string = $script->getAttribute('src');// Save the string 'jquery-3.2.0.min.js' 

我有3種方式,以檢查是否該字符串是一個jquery:

jquery(?:\\-|\\.)([\\d.]*\\d)[^/]*\\.js\\;version:\\1 
/([\\d.]+)/jquery(?:\\.min)?\\.js\\;version:\\1 
jquery.*\\.js 

在這種情況下,我如何使用這3個命令中的一個來驗證上面的字符串?

+1

做一個簡單的檢查了 「jQuery的」 用'strpos'和檢查節點是否爲空。 *(也可以使用XPath完成)*。你不需要一個正則表達式。 –

+3

標題和你的問題是不同的。 – Rahul

+0

我想你正在尋找'preg_match()':http://php.net/preg_match – rickdenhaan

回答

0

使用preg_match

的preg_match - 如果找到匹配它會打印出Match found執行正則表達式匹配

if (preg_match("/jquery.*\.js/",$string)) { 
    echo "Match found"; 
} 

。 (我剛剛使用你的一個正則表達式字符串)

我還假設你提取的是$string,因爲很難說。

Try it out

+0

警告:preg_match():分隔符不能是字母數字或反斜槓 – TheDuck

+0

我認爲這是您的正則表達式字符串@ TheDuck –

+0

在正則表達式字符串的開頭和結尾處添加'/'。 – Mikey

3

可以說是隻鏈接到jQuery的lib中使用XPath很容易地選擇腳本標籤:

$xp = new DOMXPath($doc); 
$nodeList = $xp->query('//script[.=""]/@src[contains(., "jquery")]'); 
foreach ($nodeList as $node) { 
    echo $node->nodeValue, PHP_EOL; 
} 

demo

+2

好的解決方案,使用'DOMXPath' –

相關問題