Lyall
Lyall

Reputation: 1437

PHP Substring between two specific characters

I have the following code which gives me exactly what I first needed (uppercase words after the first = in the string $data:

if (($pos = strpos($data, "=")) !== FALSE) { 
    $whatIWant = ucwords(substr($data, $pos+1)); 
}

What I now need to do is exactly the same thing, but ignore anything after (and including) the first & in the same string ($data).

My PHP is weak, please can someone tell me how to update the above to do this? I haven't been able to find the answer here but if I've missed it please tell me.

Sample strings:

destination=Apartment+TITLIS+Resort+Wohnung+721&hotelid=0123454656

destination=Rental+Apartment+Mendi+Eder+-+Saint-Jean&hotelid=01234

destination=Three-Bedroom+Holiday+Home+in+Olofstrom&hotelid=98

Upvotes: 0

Views: 78

Answers (3)

Himel Rana
Himel Rana

Reputation: 666

Your solution here: you can check here: https://3v4l.org/ohgvE

<?php 
$data = "destination=Apartment+TITLIS+Resort+Wohnung+721&hotelid=0123454656";
if (($pos = strpos($data, "=")) !== FALSE) { 
    $whatIWant = ucwords(substr($data, $pos+1)); 
    $whatIWant = explode("&", $whatIWant); // creating array from string
    $whatIWant = $whatIWant[0]; // before & is first array element
    echo "Ans1: \n";
    echo $whatIWant;
    // Output: Apartment+TITLIS+Resort+Wohnung+721
    // if you want your output with & just add & 
    echo "\n\nAns2: \n";

    $whatIWant = $whatIWant."&";

    echo $whatIWant;
    // now Output iss: 
    // Apartment+TITLIS+Resort+Wohnung+721&
}

?>

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 78994

If this query string is coming from the URL that is used to access the page (as it seems from your comment that you are using $_SERVER['QUERY_STRING']) then just use the $_GET Superglobal:

echo ucwords($_GET['destination']);

If the query string is coming from somewhere else then there is a tool for that, parse_str:

parse_str($data, $result);

Your first example query string yields:

Array
(
    [destination] => Apartment TITLIS Resort Wohnung 721
    [hotelid] => 0123454656
)

So then just:

echo ucwords($result['destination']);

Upvotes: 4

chris85
chris85

Reputation: 23892

Using the $_GET superglobal is the proper way to get a GET parameter in PHP.

$_GET['destination']

will have your destination, and it will already be url decoded.

The GET variables are passed through urldecode().

Upvotes: 1

Related Questions