Skip to content
PHP Logo

How can the strpos() and substr() functions be used to manipulate strings in PHP?

The strpos() function in PHP is used to find the position of the first occurrence of a substring within a string. The substr() function is used to extract a portion of a string based on a starting position and length. By using these two functions together, you can manipulate strings by finding specific substrings and extracting or replacing portions of the original string.

php
$string = "Hello, World!";
$substring = "World";
$pos = strpos($string, $substring);

if ($pos !== false) {
    $newString = substr($string, 0, $pos) . "PHP" . substr($string, $pos + strlen($substring));
    echo $newString; // Output: Hello, PHP!
}