Insert slash at specific place in string with preg_replace - php

I'm trying to write a function that will insert a backlash into the broken URL that for some reason is missing a second backslash after http, and I only want to return fixed version, for example
addSlash(http:/example.net) -> http://example.net
addSlash(https:/example.net`) -> https://example.net
I thought this could be solved with preg_replace in one line of code, but I can't get it to work. Using $url = 'http:/example.net' and
preg_replace("#^(https?:)(.*?)#", "\1/\2", $url);
I'm getting back / /example.net , as if 'http' is not matched and placed into \1.
Any suggestions ? I would like to avoid callbacks and anonymous function if possible, cause this is supposed to run on an older version of PHP.

/^(https:|http:)?[\\/](?![\\/])(.*)/
Something like that should work for you.
$re = "/^(https:|http:)?[\\/](?![\\/])(.*)/mi";
$str = "https:/regex101.com\nhttp:/regex101.com\nhttps://regex101.com";
$result = preg_replace($re, '$1//$2' , $str);
var_dump($result);

This should work:
preg_replace('#^(https*:)(/.*)#', '\1/\2', $url);
Or even:
preg_replace('#^(https*:)#', '\1/', $url);

Related

Which characters in urls cause file_get_contents / curl to fail?

EDIT FOR CLARIFICATION:
I would like to know which characters in a url cause file_get_contents / curl to fail.
In the example below, the only character which causes a problem is the space, so the best thing for me to do would simply be to str_replace spaces in the url with %20. Are there any other characters which also cause it to fail? If so, what are they? Is there a function which does this replacement for me?
ORIGINAL PHRASING:
I'd like to be able to download an arbitrary file by its URL, chosen by the user, and have access to it as a string. My initial reaction was:
$str = file_get_contents($url);
However, this fails on URLs like:
http://i.ebayimg.com/t/2-WAY-PHOTO-FRAME-KEY-BOX-SHABBY-CHIC-STYLE-/00/s/NjAwWDYwMA==/$(KGrHqRHJDoE-PBe-SSLBPlrnIYb Q~~60_35.JPG
Next, I tried cURL:
function file_get_contents_curl($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
However, for the same URL, cURL fails with "Invalid URL".
I've read on a number of questions here that when downloading from URLs with arbitrary characters in them, urlencode must be used. However, this results in:
http%3A%2F%2Fi.ebayimg.com%2Ft%2F2-WAY-PHOTO-FRAME-KEY-BOX-SHABBY-CHIC-STYLE-%2F00%2Fs%2FNjAwWDYwMA%3D%3D%2F%24%28KGrHqRHJDoE-PBe-SSLBPlrnIYb+Q%7E%7E60_35.JPG
which doesn't fetch either, using either method, I think because now it thinks it's a local file. What do I need to do to be able to fetch an arbitrary url?
Try this:
$url = "http://i.ebayimg.com/t/2-WAY-PHOTO-FRAME-KEY-BOX-SHABBY-CHIC-STYLE-/00/s/NjAwWDYwMA==/$(" . urlencode("KGrHqRHJDoE-PBe-SSLBPlrnIYb Q~~60_35.JPG");
$str = file_get_contents($url);
Edit: As Galen said the only problem with URL is the space and it can be fixed using str_replace as below.
$url = "http://i.ebayimg.com/t/2-WAY-PHOTO-FRAME-KEY-BOX-SHABBY-CHIC-STYLE-/00/s/NjAwWDYwMA==/$(KGrHqRHJDoE-PBe-SSLBPlrnIYb Q~~60_35.JPG";
$url = str_replace(' ', '+', $url);
$str = file_get_contents($url);

How to define a exactly match using PHP preg_replace()

I am trying to remove some parameters from a URL using PHP preg_replace(). For example, i need to remove a[]=1 from the bellow URL.
$my_url = 'www.myhost.com/filter.php?a[]=1&a[]=12&a[]=13&a[]=14'
So i am using:
$without_filter = preg_replace("/(&)?a\[\]=1/", '', $my_url);
I want to remove only a[]=1, but it is removing the portion that contains a[]=1 from the others parameters, so am i getting:
www.myhost.com/filter.php?234
Someone can help me to solve this?
What about: /a\[\]=1(&|\b)/
That way it will capture a[]=1 only if it is followed by a & or end of string.
Following the man page of preg_replace you may do something like this:
$without_filter = preg_replace("/\&(a\[\]=1)(\&|$)/", '\2', $my_url);
Or... you can always use preg_replace_callback
Use the $limit parameter of preg_replace and set it to 1, this should replace it only once. Assuming that your parameters are always sorted this way:
$without_filter = preg_replace("/(&)?a\[\]=1/", '', $my_url, 1);

replace url using preg_replace php

Hi all i know preg_replace can be used for formatting string but
i need help in that concerned area
my url will be like this
www.example.com/en/index.php
or
www.example.com/fr/index.php
what i want is to get
result as
www.example.com/index.php
i need it in php code so as to set in a session
can anyone please explain how ?
preg_replace('/www.example.com\/(.+)\/index.php/i', "www.example.com/index.php?lang=$1", $url); will do the thing
This is one way to do it:-
$newurl = preg_replace('/\/[a-z][a-z]\//', '/', $url);
Note that the search string appears with quotes and forward slashes ('/.../') and that the forward slashes in the URL then have to be escaped (\/). The language code is then matched with '[a-z][a-z]', but there are several other ways to do this and you may want something more liberal in case there are ever 3 letter codes, or caps. Equally you may need to do something tighter depending on what other URL schemes might appear.
I suspect in this instance it would be faster simply to use str_replace as follows:
$cleanedData = str_replace(array('www.example.com/en/', 'www.example.com/fr/'), '', $sourceData);
Finally i got a method my thanks to Purpletoucan
$newurl = preg_replace('/\/(en|esp|fr)\//', '/', $url);
it's working now i think!

PHP: Change only a portion of a URL string?

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 /.

How do I remove a "&" symbol from a URL using regular expressions?

how to remove a & Symbol from a url address use php regular?
for example:http://www.google.com/search?hl=en&q=php
left the & and get :http://www.google.com/search?hl=enq=php
Thanks
$url = 'http://www.google.com/search?hl=en&q=php';
$url = str_replace('&', '', $url);
I'm not sure I really understand the question. It sounds like you just want to remove & characters. That can be easily done:
$url = str_replace('&', '', $url);
You can remove it easily enough with str_replace. Why you would want to do this, however, is another matter entirely.
Are you trying to insert a URL into a page with PHP and getting validation errors due to the & symbol? In that case urlencode() might be what you really need.

Categories