search
HomeBackend DevelopmentPHP TutorialPHP regular expression in action: matching URL links
PHP regular expression in action: matching URL linksJun 23, 2023 am 08:01 AM
phpregular expressionurl match

PHP正则表达式实战:匹配URL链接

在网页开发中,经常需要处理URL链接,包括提取、验证和替换等操作。正则表达式是一种强大的字符串处理工具,可以帮助我们高效地完成这些任务。本文将结合实例介绍如何使用PHP正则表达式匹配URL链接。

一、提取URL链接中的域名

在处理一批URL链接时,往往需要将它们按照域名进行分类或统计。例如,我们要从一篇文章中提取出所有的链接,然后统计它们所属的域名。使用正则表达式可以很方便地完成这个任务。

首先,我们需要知道一个URL链接的基本格式:protocol://domain/path?query#fragment。其中,protocol表示协议,例如http、https、ftp等;domain表示域名,例如www.example.com;path表示路径,例如/index.html;query表示查询参数,例如?page=1;fragment表示片段标识符,例如#section1。

根据URL链接的格式,可以使用正则表达式提取出其中的域名。例如,以下代码可以提取出给定字符串中的所有域名:

$str = 'This is an example string with http://www.example.com and https://www.google.com';
preg_match_all('/((http|https)://[^s]+)/', $str, $matches);
$urls = $matches[0];
$domains = array();
foreach ($urls as $url) {
    $url_parts = parse_url($url);
    $domain = $url_parts['host'];
    $domains[] = $domain;
}
$domain_counts = array_count_values($domains);
print_r($domain_counts);

这段代码首先使用preg_match_all函数匹配给定字符串中的所有HTTP或HTTPS链接,并存储到$matches变量中。接着,使用parse_url函数提取出每个链接的域名,并组成一个新的数组$domains。最后,使用array_count_values函数统计每个域名出现的次数,并输出结果。运行以上代码,可以得到如下输出结果:

Array
(
    [www.example.com] => 1
    [www.google.com] => 1
)

二、验证URL链接的格式

另外一个常见的任务是验证给定字符串是否符合URL链接的格式。例如,我们需要检查用户提交的表单中是否包含有效的链接。使用正则表达式可以很轻松地完成这个任务。

以下是一个检查URL链接格式的正则表达式示例:

/^((http|https)://)?[a-z0-9]+.[a-z0-9]+.[a-z0-9]{2,}([-.]{1}[a-z0-9]{2,}){0,3}(/.*)?$/i

这个正则表达式可以匹配以下任意一种格式的URL链接:

  • http://example.com
  • https://example.com
  • example.com/path
  • example.com/path?query=1

它的具体解释如下:

  • ^ 表示匹配字符串的开始位置。
  • ((http|https)://)? 表示可选的http或https协议。
  • [a-z0-9]+.[a-z0-9]+.[a-z0-9]{2,} 表示域名部分,包括三个“.”分隔的子域名和一个顶级域名。
  • ([-.]{1}[a-z0-9]{2,}){0,3} 表示可选的子域名,包括一个“-”或“.”分隔符和两个以上的字母或数字。
  • (/.*)? 表示可选的路径,包括一个斜杠和任意字符。
  • $ 表示匹配字符串的结束位置。
  • i 表示不区分大小写。

使用上述正则表达式,可以将以下代码添加到表单验证逻辑中,来检查URL链接格式:

$url = 'http://example.com/path';
if (preg_match('/^((http|https)://)?[a-z0-9]+.[a-z0-9]+.[a-z0-9]{2,}([-.]{1}[a-z0-9]{2,}){0,3}(/.*)?$/i', $url)) {
    // URL格式正确,可以进行后续操作
} else {
    // URL格式错误,给出错误提示
}

三、替换URL链接中的域名

有时候,我们需要将一批URL链接中的域名替换为新的域名,例如在迁移网站或更改域名时。使用正则表达式可以快速实现这个替换操作。

以下代码可以将一篇文章中所有www.old-domain.com的链接替换为www.new-domain.com:

$str = 'This is an example string with http://www.old-domain.com and https://www.old-domain.com/abc.html';
$new_str = preg_replace('/(https?://)?(www.)?old-domain.com/i', '${1}${2}new-domain.com', $str);
echo $new_str;

这段代码使用preg_replace函数进行替换操作,并使用${1}和${2}表示匹配到的第一和第二个子表达式(即http或https协议和www子域名)。运行以上代码,可以得到如下输出结果:

This is an example string with http://www.new-domain.com and https://www.new-domain.com/abc.html

总结

正则表达式是一种非常强大的字符串处理工具,在PHP中也得到了广泛的应用。本文介绍了如何使用正则表达式实现URL链接的提取、验证和替换操作。希望这些例子能够帮助读者更好地掌握正则表达式的应用技巧。

The above is the detailed content of PHP regular expression in action: matching URL links. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft