I am trying to create a regular expression to do the following (within a preg_replace)
$str = 'http://www.site.com&ID=1620';
$str = 'http://www.site.com';
How would I write a preg_replace to simply remove the &ID=1620 from the string (taking into account the ID could be variable string length
thanks in advance
You could use...
$str = preg_replace('/[?&;]ID=\d+/', '', $str);
I'm assuming this is meant to be a normal URL, hence the [?&;]. If that's the case, the & should be a ?.
If it's part of a larger list of GET params, you are probably better off using...
parse_str($str, $params);
unset($params['ID']);
$str = http_build_query($params);
I'm guessing that & is not allowed as a character in the ID attribute. In that case, you can use
$result = preg_replace('/&ID=[^&]+/', '', $subject);
or (possibly better, thanks to PaulP.R.O.):
$result = preg_replace('/[?&]ID=[^&]+/', '', $subject);
This will remove &ID= (the second version would also remove ?ID=) plus any amount of characters that follow until the next & or end of string. This approach makes sure that any following attributes will be left alone:
$str = 'http://www.site.com?spam=eggs&ID=1620&foo=bar';
will be changed into
$str = 'http://www.site.com?spam=eggs&foo=bar';
You can just use parse_url
(that is if the URL is of the form: http://something.com?id1=1&id2=2):
$url = parse_url($str);
echo "http://{$url['host]}";
Related
I am trying to change all the links of a html with php preg_replace. All the uris have the following form
test.com/item/16
I want to change it to:
test.com/z/item/16
I tried the following, but it returns no changes:
$links = 'http://test.com/item/16';
preg_replace("/item","z/item",$links);
echo $links;
// output >>> http://test.com/z/item/16
You have to use delimiters as #nickb has pointed out, i.e. /your_regular_expression/. The / is the standard delimiter for regular expressions, and so, it being a special character, you'd have to escape the / you want to match by using a backslash, \/:
preg_replace("/\/item/","z/item",$links);
But luckily, you can choose your own delimiters, like #, so then no need to escape the /:
preg_replace("#/item#","z/item",$links);
Do this:
<?php
$links = 'http://test.com/item/16';
$a = preg_replace("/item/","z/item",$links);
echo $a;
preg_replace does not change the input string but instead returns a modified string....which is stored in $a variable..
You need delimiter and return of preg_replace set to variable
$links = 'http://test.com/item/16';
$links = preg_replace('/\/item/','/z/item',$links);
echo $links;
But, why don't you use just str_replace in this case?
The problem with the provided answers is that if you have more than one instance of /item in the URL, all of them will get replaced, for example a URL like:
http://items.domain.com/item/16
would get messed up, try modifying just the path:
$path = parse_url( $url, PHP_URL_PATH );
$url = str_replace( $path, '/z'.$path, $url );
sorry if my question was stupid, please someone help me to fix this issue.
i have string like
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
this $str_value is dynamic , it will change each page. now i need to replace 9 in this string as 10. add integer 1 and replace
for example if the $str_value = "http://99.99.99.99/var/test/src/158-of-box.html/251/"
then output should be
http://99.99.99.99/var/test/src/158-of-box.html/252/
i tried to replace using preg_match but i m getting wrong please somesone help me
$str = preg_replace('/[\/\d+\/]/', '10',$str_value );
$str = preg_replace('/[\/\d+\/]/', '[\/\d+\/]+1',$str_value );
Thank's for the answer, #Calimero! You've been faster than me, but I would like to post my answer, too ;-)
Another possibilty is to fetch the integer by using a group. So you don't need to trim $matches[0] to remove the slashes.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$str = preg_replace_callback('/\/([\d+])\//', function($matches) {
return '/'.($matches[1]+1).'/';
}, $str_value);
echo $str;
You need to use a callback to increment the value, it cannot be done directly in the regular expression itself, like so :
$lnk= "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$lnk= preg_replace_callback("#/\\d+/#",function($matches){return "/".(trim($matches[0],"/")+1)."/";},$lnk); // http://99.99.99.99/var/test/src/158-of-box.html/10/
Basically, the regexp will capture a pure integer number enclosed by slashes, pass it along to the callback function which will purge the integer value, increment it, then return it for replacement with padded slashes on each side.
I'd suggest also another approach based on explode and implode instead of doing any regexp stuff. In my opinion this is more readable.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/11/";
// explode the initial value by '/'
$explodedArray = explode('/', $str_value);
// get the position of the page number
$targetIndex = count($explodedArray) - 2;
// increment the value
$explodedArray[$targetIndex]++;
// implode back the original string
$new_str_value = implode('/', $explodedArray);
I am trying to strip everything that follows and includes the last ? of a given url. I am currently working with preg_replace but no luck in accomplishing the goal. This is the regex #\/[^?]*$# I am using to single out the last ?. Also is there a faster way by using substr?
Example link:
preg_replace('#\/[^?]*$#', '', $post="www.exapmle.com?26sf213132aasdf1312sdf31")
Desired Output
www.example.com
Here's how to do it with substr and strrpos:
$post = "www.exapmle.com?26sf213132aasdf1312sdf31";
$pos = strrpos($post, '?');
$result = substr($post, 0, $pos);
Add a \? at start of regex instead of \/
\?[^?]*$
\? matches a ?
[^?]*$ matches anything other than a ? until the end of string anchored by $
Example http://regex101.com/r/sW6jE7/3
$post="www.exapmle.com?26sf213132aasdf1312sdf31";
$res=preg_replace('/\?[^?]*$/', '', $post);
echo $res;
will give an output
www.example.com
EDIT
If you want to remove the entire query string from url then a slight modifiation of regex would do the work
\?.*$
which will remove anything followed by a question mark
Simply match everything from the start upto the ? symbol.
preg_match('/^[^?\n]*/', $post="www.exapmle.com?26sf213132aasdf1312sdf31", $match);
echo $match[0];
Output:
www.exapmle.com
Try this its working fine :
$host_url = "www.exapmle.com?26sf213132aasdf1312sdf31";
$part_url = strrpos($host_url, '?');
$result = substr($host_url, 0, $part_url);
echo $result;
Although OP tags regex, Surprisingly nobody suggests explode(), which is much easier.
$post = "www.exapmle.com?26sf213132aasdf1312sdf31";
$tokens = explode('?', $post);
echo $tokens[0]; // www.exapmle.com
When I've a string:
$string = 'word1="abc.3" word2="xyz.3"';
How can I replace the point with a comma after xyz in xyz.3 and keep him after abc in abc.3?
You've provided an example but not a description of when the content should be modified and when it should be kept the same. The solution might be simply:
str_replace("xyz.", "xyz", $input);
But if you explicitly want a more explicit match, say requiring a digit after the ful stop, then:
preg_replace("/xyz\.([0-9])+/", 'xyz\${1}', $input);
(not tested)
something like (sorry i did this with javascript and didn't see the PHP tag).
var stringWithPoint = 'word1="abc.3" word2="xyz.3"';
var nopoint = stringWithPoint.replace('xyz.3', 'xyz3');
in php
$str = 'word1="abc.3" word2="xyz.3"';
echo str_replace('xyz.3', 'xyz3', $str);
You can use PHP's string functions to remove the point (.).
str_replace(".", "", $word2);
It depends what are the criteria for replace or not.
You could split string into parts (use explode or preg_split), then replace dot in some parts (eg. str_replace), next join them together (implode).
how about:
$string = 'word1="abc.3" word2="xyz.3"';
echo preg_replace('/\.([^.]+)$/', ',$1', $string);
output:
word1="abc.3" word2="xyz,3"
I'm trying to remove everything after and including '.html' in a web address string. Current (failing) code is:
$input = 'http://example.com/somepage.html?foo=bar&baz=x';
$result = preg_replace("/(.html)[^.html]+$/i",'',$input);
Desired outcome:
value of $result is 'http://example.com/somepage'
Some other examples of $input that should lead to same value $result:
http://example.com/somepage
http://example.com/somepage.html
http://example.com/somepage.html?url=http://example.com/index.html
Your regular expresson is wrong, it would only match strings ending with <one char> "html" <one or more chars matching ., h, t, m or l>. Since preg_replace just returns the string "as-is" if there was no match, you'd be fine with matching the literal .html and ignoring anything after it:
$result = preg_replace('/\.html.*/', '', $input);
Why not use parse_url instead?
If you ever have issues with the syntax for preg_replace() then you can also use explode():
$input = explode(".html", $input);
$result = $input[0];