在這篇文章里,我已經(jīng)編寫了15個(gè)超有用的正則表達(dá)式,WEB開發(fā)人員都應(yīng)該將它收藏到自己的工具包。
驗(yàn)證域名
檢驗(yàn)一個(gè)字符串是否是個(gè)有效域名.
$url = "http://komunitasweb.com/"; if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) { echo "Your url is ok."; } else { echo "Wrong url."; }
從一個(gè)字符串中 突出某個(gè)單詞
這是一個(gè)非常有用的在一個(gè)字符串中匹配出某個(gè)單詞 并且突出它,非常有效的搜索結(jié)果
$text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor"; $text = preg_replace("/b(regex)b/i", '<span style="background:#5fc9f6">1</span>', $text); echo $text;
突出查詢結(jié)果在你的 WordPress 博客里就像剛才我說的,上面的那段代碼可以很方便的搜索出結(jié)果,而這里是一個(gè)更好的方式去執(zhí)行搜索在某個(gè)WordPress的博客上打開你的文件 search.php ,然后找到 方法 the_title() 然后用下面代碼替換掉它
echo $title; Now, just before the modified line, add this code: <?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '<strong>