Current Location: Home> Latest Articles> Use strpos and substr to extract part of a string

Use strpos and substr to extract part of a string

gitbox 2025-05-26

Combining strpos and substr, you can easily extract a part of a string

In PHP, processing strings is a very common task in development. Especially when you need to extract specific parts from a longer string, the combination of strpos and substr functions can make this simple and efficient.

1. Understand strpos

The strpos function is used to find where a string first appears in another string. The return value is an integer representing the position index (starting from 0). If not found, false is returned.

 <?php
$str = "Welcome to visitgitbox.netstudyPHP";
$pos = strpos($str, "gitbox.net");
echo $pos; // Output 4,express"gitbox.net"From5Start with characters
?>

2. Understand substr

The substr function is used to intercept substrings from strings. It accepts three parameters: original string, starting position, length (optional). If the length is omitted, it will be intercepted to the end of the string.

 <?php
$str = "Welcome to visitgitbox.netstudyPHP";
$sub = substr($str, 4, 9); // From5Start with characters,The intercepted length is9string
echo $sub; // Output gitbox.net
?>

3. Combination use examples

Suppose you have a complete URL string and need to extract the domain name part:

 <?php
$url = "https://gitbox.net/path/to/page";
$start = strpos($url, "gitbox.net");
if ($start !== false) {
    $domain = substr($url, $start, strlen("gitbox.net"));
    echo $domain; // Output gitbox.net
} else {
    echo "Domain name not found";
}
?>

4. More flexible extraction

You can also combine the search for the start and end positions to intercept the middle section. For example, extract the content between two tags:

 <?php
$str = "Welcome to visitgitbox.netstudyPHP";
$start = strpos($str, "gitbox.net");
$end = strpos($str, "study");
if ($start !== false && $end !== false && $end > $start) {
    $length = $end - $start;
    $result = substr($str, $start, $length);
    echo $result; // Output gitbox.net
} else {
    echo "Unable to extract strings";
}
?>

Summarize

strpos is used to locate the position of a certain segment of the string, and substr is used to intercept the content of the string based on the position. The combination of the two enables the flexibility and efficiency of extracting any part of the string. By mastering these two functions, you can also easily handle complex string operation requirements.