Tarquin
Tarquin

Reputation: 492

Trim PHP String with variable within it

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 :)

Upvotes: 0

Views: 276

Answers (4)

Robert
Robert

Reputation: 10390

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

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

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.)

Upvotes: 1

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

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

Upvotes: 1

user488187
user488187

Reputation:

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);

Upvotes: 2

Related Questions