HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Removing everything after a certain character

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
afterremovingcharactereverythingcertain

Problem

I was just writing code, and wanted to make a piece that removes everything after the character ? if it's found within the URL.

if (strstr($url, "?")) {
    $url = strstr($url, "?", true);
}


Can I make this any shorter? It doesn't feel right to type the "same thing" twice with strstr.

Solution

You're using the same variable for two different purpose. It would be readable with separate variables:

$urlWithoutParameters = strstr($url, "?", true); 
if ($urlWithoutParameters !== FALSE) {
    // if you need additional processing
}


It might be safer to use PHP's built-in parse_url function which could help handling invalid inputs too:


On seriously malformed URLs, parse_url() may return FALSE.

From Effective Java, 2nd edition, Item 47: Know and use the libraries:


By using a standard library,
you take advantage of the knowledge of the experts who wrote it and the
experience of those who used it before you.

(It's mostly a Java book but it applies here.)

Code Snippets

$urlWithoutParameters = strstr($url, "?", true); 
if ($urlWithoutParameters !== FALSE) {
    // if you need additional processing
}

Context

StackExchange Code Review Q#43269, answer score: 6

Revisions (0)

No revisions yet.