I’m working on a small hoppy project where I want to replace a specific page on a URL. Let me explain:
I’ve got the URL
http://www.example.com/article/paragraph/low/
I want to keep the URL but replace the last segment /low/ with /high/ so the new URL is:
http://www.example.com/article/paragraph/high/
I’ve tried different explode, split and splice but I just can’t seem to wrap my head around it and make it work. I can change the entire URL but not just the last segment and save it in a new variable.
I’m pretty confidence that it is a pretty straight forward case but I’ve never worked that much with arrays / string-manipulation in PHP so I’m pretty lost.
I guess that I have to first split the URL up in segments, using the "\" to separate it (I tried that but have problems by using explode("\", $string)) and then replace the last \low\ with \high\
Hope someone could help or point me in the right direction to what methods to use for doing this.
Sincere
Mestika
how about str_replace?
<?php
$newurl = str_replace('low', 'high', $oldurl);
?>
documentation;
http://php.net/manual/en/function.str-replace.php
edit;
Rik is right; if your domain (or any other part of the url for that matter) includes the string "low", this will mess up your link.
So: if your url may contain multiple 'low' 's, you will have to add an extra indicator in the script. An example of that would be including the /'s in your str_replace.
You took \ for /.
$url = explode('/', rtrim($url, '/'));
if (end($url) == 'low') {
$url[count($url)-1] = 'high';
}
$url = implode('/', $url) .'/';
Use parse_url to split the URL into its components, modify them as required (here you can use explode to split the path into its segments), and then rebuild the URL with http_build_url.
<?php
class TestURL extends PHPUnit_Framework_TestCase {
public function testURL() {
$URL = 'http://www.mydomain.com/article/paragraph/low/';
$explode = explode('/', $URL);
$explode[5] = 'high';
$expected = 'http://www.mydomain.com/article/paragraph/high/';
$actual = implode('/', $explode);
$this->assertEquals($expected, $actual);
}
}
--
phpunit simple-test.php
PHPUnit 3.4.13 by Sebastian Bergmann.
.
Time: 0 seconds, Memory: 4.75Mb
OK (1 test, 1 assertion)
This will probably be enough:
$url = "http://www.mydomain.com/article/paragraph/low/";
$newUrl = str_replace('/low/', '/high/', $url);
or with regular expressions (it allows more flexibility)
$url = "http://www.mydomain.com/article/paragraph/low/";
$newUrl = preg_replace('/low(\/?)$/', 'high$1', $url);
Note that the string approach will replace any low segment and only if it's followed by a /. The regex approach will replace low only if it's the last segment and it may not be followed by a /.
Related
I suuuuuck at regex and can't even begin to figure out how to remove everything from #edit to the end which contains a veriable of the url from this kind of URL:
https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4/edit?usp=sharing
Any help would be greatly appreciated!
Thanks!
Using strstr() with the third parameter set to true will be the cleanest, most direct non-regex approach. ...and you won't have to sweat your "suuuuucky" regex skills ;) This will isolate the substring from start of the string to the character before your search substring.
Code: (Demo)
$url = 'https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4/edit?usp=sharing';
echo strstr($url, '/edit', true); // https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4
echo "\n";
echo strstr($url, '/edit?', true); // https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4
*note: If the querystring (beginning witih ?) will always exist after /edit, adding the ? to the search substring can only improve accuracy.
Why is this the best function to call? It doesn't leverage the overhead of calling the regex engine, it doesn't generate any temporary arrays, and it is a single function call as opposed to substr()-strrpos().
If your use cases are a bit more complex and this approach is letting you down, calling parse_url() should stabilize things sufficiently to allow you extract the appropriate url components.
Code: (Demo)
$url = 'https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4/edit?usp=sharing';
$components = parse_url($url);
echo $components['scheme'], '://', $components['host'], strstr($components['path'],'/edit',true);
I believe you are trying to parse the query parameters at the end of the url. You can do so by using the explode function:
$url = "https://docs.google.com/presentation/d/1aa_xpsyJtslFJsg4UndsjDvlCe7Vu97_i6Q8zSKofy4/edit?usp=sharing";
print(explode('/edit', $url)[1]);
which will print
?usp=sharing
I want to convert relative URLs that starts with ../stuff/more.php to http://www.example.com/stuff/more.php in my RSS feed.
I used this PHP code to do so is the following:
$content = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$2$3', $content);
The result is wrong thought, it returns the URL like this
http://www.example.com/../stuff/more.php
Notice the ../ part hasn't been removed, please help!
So Basically..
This what I have: ../stuff/more.php
This is what I get (after running the code above): http://www.example.com/../stuff/more.php
This what I WANT: http://www.example.com/stuff/more.php
Adding (\.|\.\.|\/)* should work.
$content = preg_replace("#(<\s*a\s+[^>]href\s=\s*[\"'])(?!http)(../|../|/)*([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$3$4', $content);
Also, note $2$3 has been changed to $3$4
Edit:
Reduced to one alternative:
$content = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)(\.\.\/)*([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$3$4', $content);
Why don't you just replace the first 2 dots with the domain?
$result = str_replace('..', 'http://www.example.com', $contet, 1);
Use $_SERVER[HTTP_HOST] $_SERVER[REQUEST_URI] is the global variable in PHP to get the absolute url.
Well, I'll start looking at the regex. Most of it looks good (in fact, you've got a good enough regex here I'm a little surprised you're having trouble otherwise!) but the end is a bit weird -- better like this:
#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"']>)#
(Technically it would be better to capture the starting quote and make sure it's a matching ending quote, but chances are you won't have any problems there.
To remove the ../ I would do it apart from regex entirely:
foreach (array("<a href=\"http://../foo/bar\">",
"<a href=\"../foo/bar\">") as $content) {
echo "A content=$content<br />\n";
########## copy from here down to...
if (preg_match("#(<\s*a\s+[^>]*?href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"']>)#", $content, $m)) {
echo "m=<pre>".print_r($m,true)."</pre><br />\n";
if (substr($m[2], 0, 3) == '../')
$m[2] = substr($m[2], 3);
$content = $m[1].'http://www.example.com/'.$m[2].$m[3];
}
######### copy from above down to HERE
echo "B content=$content<br />\n";
}
(I included a mini-test suite around what you're looking for - you will need to take just the marked lines inside for your code.)
I found the solution thanks to everyone who helped me on this.
Here's the code I used:
$content = preg_replace("#(<a href=\"\.\.\/)#", '<a href="http://www.example.com/', $content);
it searches for <a href="../ and replace it with http://www.example.com/ it's not general but this works for me.
here's my code snippet to start with:
$url = $_SERVER["REQUEST_URI"]; // gives /test/test/ from http://example.org/test/test/
echo"$url";
trim ( $url ,'/' );
echo"$url";
I use this in combination with .htaccess rewrite, I’ll get the information from the URL and generate the page for the user with PHP using explode.
I don't want .htaccess to interpret the URL, which is probably better, but I am more common with PHP and I think it’s more flexible.
I already read this (which basically is what I want):
Best way to remove trailing slashes in URLs with PHP
The only problem is, that trim doesn’t trim the leading slashes. Why?
But actually it should work. Replacing '/' with "/", '\47' or '\x2F' doesn’t change anything.
It neither works online nor on localhost.
What am I doing wrong?
The trim function returns the trimmed string. It doesn't modify the original. Your third line should be:
$url = trim($url, '/');
This can be done in one line...
echo trim($_SERVER['REQUEST_URI'], '/');
You need to do:
$url = trim($url, '/');
You also should just do
echo $url;
It is faster.
trim does not modify the original. You'll need to do something such as:
$url = $_SERVER["REQUEST_URI"]; // gives /test/test/ from http://example.org/test/test/
echo"$url";
$url = trim ( $url ,'/' );
echo"$url";
I am creating a PHP proxy where it accepts a url and confirms it is on my list of servers.
When importing the url from the application i ran it to an issue where i needed 2 parser tags. i need it to split along a "\?" tag as well as a string, in my case, "export?"
i am using preg for the first tag. Does this accept the strings like my export tag or is there some other method for doing this?
please le me know how this is accomplished or if you have more questions.
As ircmaxell has already stated in the comments, PHP does already have a function to parse a URL: parse_url.
And when you have the URL path (I assume your export? the path suffix plus the query indicator), you can use explode to split the path into its path segments:
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', $path);
You can then get the last path segment with one of the following:
end($segments)
$segments[count($segments)-1]
And to cope with trailing slashes, you can use rtrim($path, '/') to remove them.
All together:
$url = 'http://www.example.com/subfolders/export?';
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', rtrim($path, '/'));
echo end($segments);
A regular expression should do the trick, something like the below would work. This is what Django uses in their URL dispatcher
r'^export/$'
Regular expressions are strings matches that may also include variable matches. Because ? is included within ?, you have to do your split twice. Once on export? first, and a second pass on each of those with ? as your delimiter. As written below, you're just splitting on either of two different strings.
$first = preg_split('export\?', ...);
for ($first) {
array_push ($second,preg_split('\?', ...)');
}
That isn't perfectly valid PHP, but I hope it is close enough pseudocode.
Hey guys i ended up using an explode which looked for the string (export?) and then i used the preg split command to search for the \?. this provided me with the protion i was looking for. thanks guys.
I am trying to get the page or last directory name from a url
for example if the url is: http://www.example.com/dir/ i want it to return dir or if the passed url is http://www.example.com/page.php I want it to return page Notice I do not want the trailing slash or file extension.
I tried this:
$regex = "/.*\.(com|gov|org|net|mil|edu)/([a-z_\-]+).*/i";
$name = strtolower(preg_replace($regex,"$2",$url));
I ran this regex in PHP and it returned nothing. (however I tested the same regex in ActionScript and it worked!)
So what am I doing wrong here, how do I get what I want?
Thanks!!!
Don't use / as the regex delimiter if it also contains slashes. Try this:
$regex = "#^.*\.(com|gov|org|net|mil|edu)/([a-z_\-]+).*$#i";
You may try tho escape the "/" in the middle. That simply closes your regex. So this may work:
$regex = "/.*\.(com|gov|org|net|mil|edu)\/([a-z_\-]+).*/i";
You may also make the regex somewhat more general, but that's another problem.
You can use this
array_pop(explode('/', $url));
Then apply a simple regex to remove any file extension
Assuming you want to match the entire address after the domain portion:
$regex = "%://[^/]+/([^?#]+)%i";
The above assumes a URL of the format extension://domainpart/everythingelse.
Then again, it seems that the problem here isn't that your RegEx isn't powerful enough, just mistyped (closing delimiter in the middle of the string). I'll leave this up for posterity, but I strongly recommend you check out PHP's parse_url() method.
This should adequately deliver:
substr($s = basename($_SERVER['REQUEST_URI']), 0, strrpos($s,'.') ?: strlen($s))
But this is better:
preg_replace('/[#\.\?].*/','',basename($path));
Although, your example is short, so I cannot tell if you want to preserve the entire path or just the last element of it. The preceding example will only preserve the last piece, but this should save the whole path while being generic enough to work with just about anything that can be thrown at you:
preg_replace('~(?:/$|[#\.\?].*)~','',substr(parse_url($path, PHP_URL_PATH),1));
As much as I personally love using regular expressions, more 'crude' (for want of a better word) string functions might be a good alternative for you. The snippet below uses sscanf to parse the path part of the URL for the first bunch of letters.
$url = "http://www.example.com/page.php";
$path = parse_url($url, PHP_URL_PATH);
sscanf($path, '/%[a-z]', $part);
// $part = "page";
This expression:
(?<=^[^:]+://[^.]+(?:\.[^.]+)*/)[^/]*(?=\.[^.]+$|/$)
Gives the following results:
http://www.example.com/dir/ dir
http://www.example.com/foo/dir/ dir
http://www.example.com/page.php page
http://www.example.com/foo/page.php page
Apologies in advance if this is not valid PHP regex - I tested it using RegexBuddy.
Save yourself the regular expression and make PHP's other functions feel more loved.
$url = "http://www.example.com/page.php";
$filename = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);
Warning: for PHP 5.2 and up.