0

I am currently trying to format url links with parse_url. My goal is to parse the link every time it has the following characters &p (in that order) in it. The if statement is there to check for these characters the in the url before deciding to parse the link or not. For example, if the link has the characters &p (in that order) then it will parse the link and format to my desired choice. I have been able to figure the parsing part but how would I be able to check for these characters &p (in that order)? If you see below example, I only want to remove & from the link.

if($url == '&p' ) // not sure how to check
{
$parsed_url = parse_url($url);
$fragment = $parsed_url['fragment'];
$fragment_parts = explode('/', $fragment);
$formatted_url = array_pop('http://www.website.com?p=$1',$url);
}
else    
{   
// do something else
}

Example:

Input: http://www.website.com?&p=107

Output: 'http://www.website.com?p=107

1
  • Why don't you always parse the URL and reassemble it? If it was already properly formatted, it won't change, otherwise it will be fixed. Commented Jan 27, 2013 at 1:50

2 Answers 2

1

You can use str_replace function to replace this &p string with p.

$url = "http://www.website.com?&p=107";
$url = str_replace("&p", "p", $url);
echo $url; // will print http://www.website.com?p=107

Test here

For more complex text processing you may use preg_replace().

Sign up to request clarification or add additional context in comments.

2 Comments

yes, but how can i check in the if statement if the string has the characters &p or not?
You can use if(isnull(strpos($url, "&p")) {do something if not found}.
0

If you just need to check if the url has got the ?&p just use strpos:

<?php
if(strpos($url, '?&p') !== false) {
//your magic
}
?>

Otherwise if you're trying to handle a bad request you can do something like:

<?php
$url = $_SERVER['REQUEST_URI']; // will have the /?&p=123
if(strpos($url, '?&p') !== false) {
    $url = str_replace("&p", "p", $url); // now you've only got ?p=123
    //then do what ever you like 
    //redirect to the appropriate URL or you can set the $_GET['p'] e.g.
    header("Location: /".$url);
    //or
    $parsed = parse_str($url, $get);
    $_GET['p'] = $get['?p'];
}
?>

Comments

Your Answer

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