What are the advantages and disadvantages of using substr() versus explode() in PHP to extract values from URLs?
When extracting values from URLs in PHP, substr() can be used to extract a portion of a string based on character positions, while explode() can be used to split a string into an array based on a delimiter. The advantage of using substr() is that it is simpler and more straightforward for extracting specific parts of a URL, such as extracting a substring between two known characters. On the other hand, explode() is more flexible as it can handle URLs with varying structures by splitting the string based on a delimiter like "/". However, the disadvantage of using substr() is that it may require more complex logic to handle URLs with dynamic lengths or structures, while explode() may not be suitable for extracting specific parts of a URL if the delimiter is not consistent.
$url = "https://www.example.com/page/123";
// Using substr() to extract the page number
$page_number = substr($url, strrpos($url, '/') + 1);
echo $page_number; // Output: 123