How to get a substring between two strings in PHP?
You can use the strpos
function to find the position of the first occurrence of a substring in a string, and then use the substr
function to extract the desired substring.
Here's an example:
<?php
$string = "The quick brown fox jumps over the lazy dog.";
$start = "quick";
$end = "fox";
$start_pos = strpos($string, $start);
$end_pos = strpos($string, $end);
$substring = substr($string, $start_pos, $end_pos - $start_pos + strlen($end));
echo $substring; // prints "quick brown fox"
Watch a video course
Learn object oriented PHP
This example will print the substring starting at the first occurrence of "quick" and ending at the first occurrence of "fox", including both of those substrings.
Note that the strpos
function will return FALSE
if the substring is not found, so you may want to check for this case and handle it appropriately.