I have a string which contains a varying number of Url's. I would like to remove the "?category_id=x" part of every Url. x will be a changing number.
var old_string = "some text <a href='/platforms/item/something?category_id=x'>some text</a> some more text <a href='/platforms/item/something?category_id=x'>some text</a>..."
var new_string = "some text <a href='/platforms/item/something'>some text</a> some more text <a href='/platforms/item/something'>some text</a>...."
How can I do this. Regex?
Answers using parse_url are best if you've already extracted the URLs from your string. I'm assuming you have not.
<?php
$old_string = "some text <a href='/platforms/item/something?category_id=x'>some text</a> some more text <a href='/platforms/item/something?category_id=x'>some text</a>...";
// if you know there won't be any other url parameters:
$new_string = preg_replace('!\?category_id=(x|\d+)!','', $old_string );
// otherwise, remove query string from all URLs:
$new_string = preg_replace('!(href=(?:\'|")[^\?\'"]+)\?[^\'"#]*!','\1', $old_string );
Your code looks like JavaScript though. The second regexp in JS would be:
old_string.replace( /(href=(?:"|')[^\?'"]+)\?[^'"#]*/g, '$1' );
There is the parse_url function that allows to separate the components of an url string.
<?php
$url = '//www.example.com/path?googleguy=googley';
var_dump(parse_url($url));
?>
Output:-
array(3) {
["host"]=>
string(15) "www.example.com"
["path"]=>
string(5) "/path"
["query"]=>
string(17) "googleguy=googley"
}
<?php
$old_string = "some text <a href='/platforms/item/something?category_id=x'>some text</a> some more text <a href='/platforms/item/something?category_id=x'>some text</a>...";
preg_match( '/<a href=\'(.*?)\'>/', $old_string, $match );
$url = parse_url($match[1]) ;
$new_string = "some text <a href='".$url["host"].$url["path"];
$new_string .= "'>some text</a> some more text <a href='/platforms/item/something? category_id=x'>some text</a>...";
echo htmlentities($new_string);
//output
// some text <a href='/platforms/item/something'>some text</a> some more text <a href='/platforms/item/something?category_id=x'>some text</a>...
?>