10个实用的PHP正则表达式汇总(2)
复制代码 代码如下: $url = "http://ansoncheung.tk/"; 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 {
复制代码 代码如下:
$url = "http://ansoncheung.tk/";
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.";
}
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.";
}
9. 从特定URL中提取域名
复制代码 代码如下:
$url = "http://ansoncheung.tk/articles";
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
echo $host;
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
echo $host;
10. 将文中关键词高亮显示
复制代码 代码如下:
$text = "Sample sentence from AnsonCheung.tk, regular expression 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;
$text = preg_replace("/\b(regex)\b/i", '<span style="background:#5fc9f6">\1</span>', $text);
echo $text;
希望本文所述对大家的PHP程序设计有所帮助。
- 上一篇:PHP函数实现分页含文本分页和数字分页
- 下一篇:PHP中怎样防止SQL注入分析
精彩图集
精彩文章