如何使用 PHP 检查 URL 是否包含特定字符串


什么是 PHP?

PHP(超文本预处理器)是一种流行的脚本语言,专为 Web 开发而设计。它广泛用于创建动态和交互式的网页。PHP 代码可以直接嵌入到 HTML 中,允许开发人员无缝地混合 PHP 和 HTML。PHP 可以连接到数据库、处理表单数据、生成动态内容、处理文件上传、与服务器交互以及执行各种服务器端任务。它支持各种 Web 开发框架,例如 Laravel、Symfony 和 CodeIgniter,这些框架为构建 Web 应用程序提供了额外的工具和功能。PHP 是一种开源语言,拥有庞大的社区、丰富的文档以及丰富的库和扩展生态系统。

如何使用 PHP 检查 URL 是否包含特定字符串

使用 strpos() 函数

PHP 中的 strpos() 函数用于查找子字符串在字符串中首次出现的起始位置。如果子字符串存在,则函数返回子字符串的起始索引;否则,如果在字符串(URL)中未找到子字符串,则返回 False。

语法

int strpos( $String, $Substring )

$字符串:此参数保存执行搜索的文本。

$子字符串:此参数保存要搜索的模式或子字符串。

示例

<?php
$url = "https://tutorialspoint.com/php/";
// Check if the URL contains the string "example"
if (strpos($url, "tutor") !== false) {
   echo "The URL contains the string 'tutor'.";
} else {
   echo "The URL does not contain the string 'tutor'.";
}
// Another search substring
$key = 'hyderabad';
if (strpos($url, $key) == false) {
   echo $key . ' does not exists in the URL.';
}
else {
   echo $key . ' exists in the URL.';
}
?>

输出

The URL contains the string 'tutor'.hyderabad does not exists in the URL.

使用 preg_match() 函数

PHP 中的 preg_match() 函数用于使用正则表达式进行模式匹配。它允许您检查字符串中是否存在某个模式。

语法

preg_match( $pattern, $subject )

参数

$模式:它是作为字符串的搜索正则表达式模式。

$主题:它是搜索正则表达式模式的文本字符串。

示例

<?php
// PHP program to find exach match substring
// Given a URL
$url = 'https://www.google.co.in/';
// Here '\b' represents the block
// This pattern search gfg as whole words
$pattern = '/\bgoogle\b/';
if (preg_match($pattern, $url) == false) {
	echo 'google does not exist in the URL. <br>';
} else {
	echo 'google exist in the URL .<br>';
}
// Given another URL
$url2 = 'https://www.google.co.in/';
// This pattern search function as whole words
$pattern = '/\bchrome\b/';
if (preg_match($pattern, $url2) == false) {
	echo 'chrome does not exist in the URL.';
} else {
	'chrome exist in the URL.';
}
?>

输出

google exist in the URL.
chrome does not exist in the URL.

结论

总之,要检查 PHP 中的 URL 是否包含特定字符串,您可以使用 strpos() 或 preg_match() 函数。strpos() 函数在字符串中搜索子字符串,并返回其首次出现的起始位置,如果未找到则返回 false。它适用于简单的字符串匹配。例如,strpos($url, $substring) 可用于检查 URL 是否包含特定字符串。

另一方面,preg_match() 允许使用正则表达式进行模式匹配。它在字符串中搜索模式,并返回匹配次数或在未找到匹配项时返回 false。正则表达式提供了更多灵活性和高级模式匹配功能。例如,preg_match("/pattern/", $url) 可用于检查 URL 是否包含特定模式。这两个函数都可用于 URL 匹配,但 preg_match() 提供了更强大的模式匹配功能,而 strpos() 对于基本字符串匹配来说更简单且更快。

更新于: 2023-07-31

4K+ 次查看

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.