0

I seek your assistance once more with a small problem I am having, the solution is potentially obvious/looking at me in the face, but I have yet to resolve my issue.

I have the need to trim a string which happens to have a variable within it. (the string is actually a URL)

An example String/URL:

/portal/index.php?module=SerialDB&page=listing&returnmsg=3

&returnmsg=3 can be a range of numbers from 0 to 100, as well as, in some cases, text. This is the variable I need to trim as I am hoping to store the rest of the string/URL into a database. The following is the result I seek;

/portal/index.php?module=SerialDB&page=listing

I have tried the following code just to see if it could appropriate the function I require, but unfortunately it is more specific and won't trim unless it gets an EXACT match.

$str = "/portal/index.php?module=SerialDB&returnmsg=3";
echo $str . "<br>"; // Test to see full string
echo chop($str,"&returnmsg="); // Attempt to trim the string

If anyone is up to the task of assisting I would be greatly appreciative. As with all my questions, I would also like to understand what is happening as opposed to just being handed the code so I can use it confidently in the future.

Thanks once again guys :)

4
  • 1
    preg_replace (&returnmsg=*) with blank Commented Feb 9, 2015 at 1:53
  • is this param always the last (when present)? and does your url contain an anchor part? Commented Feb 9, 2015 at 1:56
  • Surely the result you seek is not '/portal/index.php?module=SerialDB&page=listing', otherwise why not use php's substring function:echo substr($str, 0, 46); Commented Feb 9, 2015 at 2:02
  • Yes the param is always the last when present, however the rest of the url (like &page= and &module= can differ, as well as additional or less params) can differ dramatically in length Commented Feb 9, 2015 at 2:06

4 Answers 4

2

A quick way that doesn't depend on parameter order is just to take apart the pieces, pick out what you want, and then put them back together again (you can look up the various PHP functions for more details):

$urlParts = parse_url($url);
parse_str($urlParts['query'], $queryParts);
$returnMsg = $queryParts['returnmsg'];
unset($queryParts['returnmsg']);
$urlParts['query'] = http_build_query($queryParts);
$url = http_build_url($urlParts);
Sign up to request clarification or add additional context in comments.

1 Comment

This code generated an error for me. Hudixt appears to have corrected it but the output isnt exactly what I want, however thank you for showing me these functions, they will be very useful for me in the future. =)
2

Simple. The concept is known as slicing.

$url = "/portal/index.php?module=SerialDB&page=listing&returnmsg=3";

$new_url = substr( $url, 0, strrpos( $url, '&') );

result is: /portal/index.php?module=SerialDB&page=listing

The substr() function returns part of a string. It takes three parameters. Parameter #1 is the string you are going to extract from, parameter #2 is where are you going to start from and parameter #3 is the length of the slice or how many characters you want to extract.

The strrpos() function returns the position/index of the last occurrence of a substring in a string. Example: if you have the string "zazz" the position of the last z will be returned. You can think of it as "string reverse position". This function accepts three parameters. I will only cover two as this is the number I used in this example. Parameter #1 is the string you are searching in, parameter #2 is the needle or what you are looking for, in your case the &. As I mentioned in the beginning of this paragraph, it returns the position in the form of an integer. In your case that number was 46.

So the strrpos() as the third parameter in substr() is telling it up to where to slice the string. Upon completion it returns the segment that you wanted to extract.

It would be helpful if you read the PHP Manual and looked over the available functions that might help you in the future. You can combine these functions in various ways to solve your problems.

http://php.net/manual/en/funcref.php

2 Comments

Could you explain the breakdown of how it accomplishes only slicing off the very last & in the string?
I figured that was the case, I realized that somehow it was picking up the LAST occurrence but didn't understand how. Thank you for the explanation, you have earned an upvote for your assistance. I appreciate it.
1

If returnmsg is always the last param (and not the first) in your url and if your url doesn't contain an anchor, so in short the param is always at the end, you can solve the problem with a simple explode:

$url = explode('&returnmsg=', $url)[0];

(you split the string with &returnmsg= and you keep the first part).

otherwise as suggested in comments you can use a regex replacement:

$url = preg_replace('~[?&]returnmsg=[^&#]*~', '', $url);

pattern details:

~            # pattern delimiter
[?&]         # a literal "?" or a literal "&"
returnmsg=
[^&#]*       # any characters except "&" or "#" zero or more times
~

(for the two ways, if the param is not present, the url stay unchanged.)

1 Comment

using the preg_replace function offered here worked perfectly for the given scenario. Much thanks.
1

I don't weather it comes in starting or in end so if it comes in end then use the code below.

<?php
    $url="/portal/index.php?module=SerialDB&page=listing&returnmsg=3";
    $array= explode("&",$url);
    $new_url="";
    foreach($array as $p){
    if(strpos($p,"returnmsg")===false){
    $new_url .=$p."&";
    }
    }
    echo rtrim($new_url, "&");

The above code is exploding the array & and then running a foreach loop to join them. @Bobdye answer is also correct but there is a bit problem in that code, that wasn't running for me. Use the code below

<?php
     $url="/portal/index.php?module=SerialDB&page=listing&returnmsg=3";
    $urlParts = parse_url($url);
    parse_str($urlParts['query'], $queryParts);
    $returnMsg = $queryParts['returnmsg'];
    unset($queryParts['returnmsg']);
    $urlParts['query'] = http_build_query($queryParts);
    $url = http_build_query($urlParts);
    var_dump($url);

Hope this helps you

2 Comments

I am upvoting this answer as the first code snippet you offered works a treat, however I would like to advise that I am selecting Casimir's answer simply because in my particular use, it is able to give me the output I desire (like yours) in a much faster operation with less code.
@Tarquin I know the answer given by Casmir is the best answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.