how change part of url by preg_replace? - php

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 );

Related

PHP: How to strip all types of extensions from URL (incl. period)

I am new to PHP and hope someone can help me with this.
I want PHP to give me the name of the current page of my website.
The important thing is that I need this without any leading slashes and without any trailing extensions etc., just the plain page name.
Example:
The URL of a page is http://www.myurl.com/index.php?lang=en
In this case it should only return "index".
I found a way to get rid of the leading part using the following but have trouble to remove the trailing part since this is variable (it can be just .php or .php?lang=en or .php=lang=de etc.).
$pageName = basename($_SERVER["REQUEST_URI"]);
The only thing I found is the following but this doesn't cover the variable extension part:
$pageName = basename($_SERVER["REQUEST_URI"], ".php");
Can someone tell me how to get rid of the trailing part as well ?
Many thanks in advance,
Mike
You can use parse_url in combination with pathinfo:
<?php
$input = 'http://www.myurl.com/index.php?lang=en';
$output = pathinfo(parse_url($input, PHP_URL_PATH), PATHINFO_FILENAME);
var_dump($output); // => index
demo: https://eval.in/382330
One possible way is:
$url = "http://www.myurl.com/index.php?lang=en";
preg_match('/\/([\w-_]+)\.php/i',$url,$match);
echo $match[1];
If you need help with the regex look here:
https://regex101.com/r/cM8sS3/1
here is simplest solution.
$pagename = basename($_SERVER['PHP_SELF']);
$a = explode(".",$pagename);
echo $a[0];
A tutorial on how to do it
With an .htaccess file you can:
Redirect the user to different page
Password protect a specific directory
Block users by IP Preventing hot
linking of your images
Rewrite URIs
Specify your own Error Documents
Try this
//return url
$pageName = base64_decode($_GET["return_url"]);
function Url($pageName) {
$pageName= strtolower($pageName);
$pageName= str_replace('.',' ',$pageName);
$pageName= preg_replace("/[^a-z0-9_\s-]/", "", $pageName);
$pageName= preg_replace("/[\s-]+/", " ", $pageName);
$pageName= preg_replace("/[\s_]/", "-", $pageName);
return $pageName ;
}
$cleanurl=Url($pageName);
echo $cleanurl;
This is a situation where I would just use a regular expression. Here's the code:
$pagename = basename("http://www.myurl.com/index.php?lang=en");
$pagename = preg_replace("/\..*/", "", $pagename);
You can see a working demo here: https://ideone.com/RdrHzc
The first argument is an expression that matches for a literal period followed by any number of characters. The second argument tells the function to replace the matched string with an empty string, and the last argument is the variable to operate on.

PHP regex: How to remove ?file in url?

My url like this:
http://mywebsite.com/movies/937-lan-kwai-fong-2?file=Rae-Ingram&q=
http://mywebsite.com/movies/937-big-daddy?file=something&q=
I want to get "lan-kwai-fong-2" and "big-daddy", so I use this code but it doesn't work. Please help me fix it ! If you can shorten it, it is so great !
$url= $_SERVER['REQUEST_URI'];
preg_replace('/\?file.*/','',$url);
preg_match('/[a-z][\w\-]+$/',$url,$matches);
$matches= str_replace("-"," ",$matches[0]);
First there are issue with your code which im going to go over because they are general things:
preg_replace does not work by reference so you are never actually modifying the url. You need to assign the result of the replace to a variable:
// this would ovewrite the current value of url with the replaced value
$url = preg_replace('/\?file.*/','',$url);
It is possible that preg_match will not find anything so you need to test the result
// it should also be noted that sometimes you may need a more exact test here
// because it can return false (if theres an error) or 0 (if there is no match)
if (preg_match('/[a-z][\w\-]+$/',$url,$matches)) {
// do stuff
}
Now with that out of the way you are making this more difficult than it needs to be. There are specific function for working with urls parse_url and parse_str.
You can use these to easily work with the information:
$urlInfo = parse_url($_SERVER['REQUEST_URI']);
$movie = basename($urlInfo['path']); // yields 937-the-movie-title
Just replace
preg_replace('/\?file.*/','',$url);
with
$url= preg_replace('/\?file.*/','',$url);
Regex works, and parse_url is the right way to do it. But for something quick and dirty I would usually use explode. I think it's clearer.
#list($path, $query) = explode("?", $url, 2); // separate path from query
$match = array_pop(explode("/", $path)); // get last part of path
How about this:
$url = $_SERVER['REQUEST_URI'];
preg_match('/\/[^-]+-([^?]+)\?/', $url, $matches);
$str = isset($matches[1]) ? $matches[1] : false;`
match last '/'
match anything besides '-' until '-'
capture anything besides '?' until (not including) '?'

String replace with wildcard

I have a string http://localhost:9000/category that I want to replace with category.html, i.e. strip everything before /category and add .html.
But can't find a way to do this with str_replace.
You want to use parse_url in this case:
$parts = parse_url($url);
$file = $parts['path'].'.html';
Or something along that line. Experiment a bit with it.
Ismael Miguel suggested this shorter version, and I like it:
$file = parse_url($url,PHP_URL_PATH).'.html';
Much better than a ^*!$(\*)+ regular expression.
.*\/(\S+)
Try this.Replace by $1.html.see demo .
http://regex101.com/r/nA6hN9/43
Use preg_replace instead of str_replace
Regex:
.*\/(.+)
Replacement string:
$1.html
DEMO
$input = "http://localhost:9000/category";
echo preg_replace("~.*/(.+)~", '$1.html', $input)
Output:
category.html
A solution without regex:
<?php
$url = 'http://localhost:9000/category';
echo #end(explode('/',$url)).'.html';
?>
This splits the string and gets the last part, and appends .html.
Note that this won't work if the input ends with / (e.g.: $url = 'http://localhost:9000/category/';)
Also note that this relies on non-standard behavior and can be easily changed, this was just made as a one-liner. You can make $parts=explode([...]); echo end($parts).'.html'; instead.
If the input ends with / occasionally, we can do like this, to avoid problems:
<?php
$url = 'http://localhost:9000/category/';
echo #end(explode('/',rtrim($url,'/'))).'.html';
?>

Get vine video id using php

I need to get the vine video id from the url
so the output from link like this
https://vine.co/v/bXidIgMnIPJ
be like this
bXidIgMnIPJ
I tried to use code form other question here for Vimeo (NOT VINE)
Get img thumbnails from Vimeo?
This what I tried to use but I did not succeed
$url = 'https://vine.co/v/bXidIgMnIPJ';
preg_replace('~^https://(?:www\.)?vine\.co/(?:clip:)?(\d+)~','$1',$url)
basename maybe?
<?php
$url = 'https://vine.co/v/bXidIgMnIPJ';
var_dump(basename($url));
http://codepad.org/vZiFP27y
Assuming it will always be in that format, you can just split the url by the / delimiter. Regex is not needed for a simple url such as this.
$id = end(explode('/', $url));
Referring to as the question is asked here is a solution for preg_replace:
$s = 'https://vine.co/v/bXidIgMnIPJ';
$new_s = preg_replace('/^.*\//','',$s);
echo $new_s;
// => bXidIgMnIPJ
or if you need to validate that an input string is indeed a link to vine.co :
$new_s = preg_replace('/^(https?:\/\/)?(www\.)?vine\.co.*\//','',$s);
I don't know if that /v/ part is always present or is it always v... if it is then it may also be added to regex for stricter validation:
$new_s = preg_replace('/^(https?:\/\/)?(www\.)?vine\.co\/v\//','',$s);
Here's what I am using:
function getVineId($url) {
preg_match("#(?<=vine.co/v/)[0-9A-Za-z]+#", $url, $matches);
if (isset($matches[0])) {
return $matches[0];
}
return false;
}
I used a look-behind to ensure "vine.co/v/" always precedes the ID, while ignoring if the url is HTTP or HTTPS (or if it lacks a protocol altogether). It assumes the ID is alphanumeric, of any length. It will ignore any characters or parameters after the id (like Google campaign tracking parameters, etc).
I used the "#" delimiter so I wouldn't have to escape the forward slashes (/), for a cleaner look.
explode the string with '/' and the last string is what you are looking for :) Code:
$vars = explode("/",$url);
echo $vars[count($vars)-1];
$url = 'https://vine.co/v/b2PFre2auF5';
$regex = '/^http(?:s?):\/\/(?:www\.)?vine\.co\/v\/([a-zA-Z0-9]{1,13})$/';
preg_match($regex,$url,$m);
print_r($m);
1. b2PFre2auF5

regular expression to remove ID=1234 from a string (PHP)

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]}";

Categories