How to check if URL Contain Certain String using PHP

In PHP, you can check if a URL contains a certain string using builtin functions like strpos() for simple substring matching or preg_match() for pattern matching with regular expressions.

Using strpos() Function

The strpos() function finds the position of the first occurrence of a substring within a string. It returns the starting index if found, or false if the substring doesn't exist.

Syntax

int strpos( $string, $substring )

$string: The text where searching is performed.

$substring: The pattern or substring to be searched.

Example

<?php
$url = "https://www.tutorialspoint.com/php/";

// Check if the URL contains the string "tutor"
if (strpos($url, "tutor") !== false) {
    echo "The URL contains the string 'tutor'.<br>";
} else {
    echo "The URL does not contain the string 'tutor'.<br>";
}

// Another search substring
$key = 'hyderabad';
if (strpos($url, $key) === false) {
    echo $key . ' does not exist in the URL.';
} else {
    echo $key . ' exists in the URL.';
}
?>
The URL contains the string 'tutor'.
hyderabad does not exist in the URL.

Using preg_match() Function

The preg_match() function performs pattern matching using regular expressions, allowing more complex pattern searches.

Syntax

preg_match( $pattern, $subject )

$pattern: The regular expression pattern for searching.

$subject: The text string to search within.

Example

<?php
// Given a URL
$url = 'https://www.google.co.in/';

// '\b' represents word boundary
// This pattern searches for 'google' as a whole word
$pattern = '/\bgoogle\b/';
if (preg_match($pattern, $url)) {
    echo 'google exists in the URL.<br>';
} else {
    echo 'google does not exist in the URL.<br>';
}

// Search for another pattern
$pattern2 = '/\bchrome\b/';
if (preg_match($pattern2, $url)) {
    echo 'chrome exists in the URL.';
} else {
    echo 'chrome does not exist in the URL.';
}
?>
google exists in the URL.
chrome does not exist in the URL.

Comparison

Method Use Case Performance Features
strpos() Simple substring search Faster Basic matching
preg_match() Pattern matching Slower Regular expressions, word boundaries

Conclusion

Use strpos() for simple substring matching in URLs as it's faster and sufficient for basic needs. Choose preg_match() when you need advanced pattern matching with regular expressions for more complex URL validation.

Updated on: 2026-03-15T10:28:03+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements