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

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

什么是PHP

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

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

使用strpos()函数

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

语法

int strpos( String,Substring )

$ String :该参数保存要进行搜索的文本。

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

示例

<?php
url = "https://www.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) {
   echokey . ' 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 )

参数

$ 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 wordspattern = '/\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 wordspattern = '/\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()在基本的字符串匹配方面更简单且更快速。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程