Remove only 3 characters after a specific string - php

Hi I have this string for example
http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/it/clients/
I want to remove only 3 characters after bbbb-bbbbbbbbbb-2/, so basically I want to remove the it/ part (This it/ part may not always be it but it can be es/ or en/ or different languages always 2 characters )

The following will work provided the the URL structure doesn't change. I assume you're wanting to remove the language part of the URL.
<?php
$url = "http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/it/clients/";
$parsedURL = parse_url($url);
$path = explode('/', $parsedURL['path']);
unset($path[2]);
$url = "{$parsedURL['scheme']}://{$parsedURL['host']}";
$url .= implode('/', $path);
var_dump($url);
// string(47) "http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/clients/"

You can use regex to selecting target part of string and run it in preg_replace().
$url = "http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/it/clients/";
echo preg_replace("#(.*)\w{2}/([^/]+/)$#", "$1$2", $url);
See result of code in demo

Define your languages in an array. If a language is not defined in the array URL will be the same.
$mLanguages = ["en","it","bg","gr"];
$mURL = "http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/it/clients/";
$mURL = removeLanguageFromURL($mURL, $mLanguages);
echo $mURL; // Output http://aaa-aaaa.com/bbbb-bbbbbbbbbb-2/clients/
function removeLanguageFromUrl($mURL, $mLanguages){
foreach($mLanguages as $language){ // Search languages
if(strpos($mURL, $language) !== false) // If language is found in url remove it
$mURL = str_replace('/' . $language,'', $mURL);
}
return $mURL;
}

Related

Remove characters from beginning and end string

I want to ouput only MYID from URL. What I did so far:
$url = "https://whatever.expamle.com/display/MYID?out=1234567890?Browser=0?OS=1";
echo substr($url, 0, strpos($url, "?out="));
output: https://whatever.expamle.com/display/MYID
$url = preg_replace('#^https?://whatever.expamle.com/display/#', '', $url);
echo $url;
ouput: MYID?out=1234567890?Browser=0?OS=1
How can I combine this? Thanks.
For a more general solution, we can use regex with preg_match_all:
$url = "https://whatever.expamle.com/display/MYID?out=1234567890?Browser=0?OS=1";
preg_match_all("/\/([^\/]+?)\?/", $url, $matches);
print_r($matches[1][0]); // MYID
When the string is always a Uniform Resource Locator (URL), like you present it in your question,
given the following string:
$url = "https://whatever.expamle.com/display/MYID?out=1234567890?Browser=0?OS=1";
you can benefit from parsing it first:
$parts = parse_url($url);
and then making use of the fact that MYID is the last path component:
$str = preg_replace(
'~^.*/(?=[^/]*$)~' /* everything but the last path component */,
'',
$parts['path']
);
echo $str, "\n"; # MYID
and then depending on your needs, you can combine with any of the other parts, for example just the last path component with the query string:
echo "$str?$parts[query]", "\n"; # MYID?out=1234567890?Browser=0?OS=1
Point in case is: If the string already represents structured data, use a dedicated parser to divide it (cut it in smaller pieces). It is then easier to come to the results you're looking for.
If you're on Linux/Unix, it is even more easy and works without a regular expression as the basename() function returns the paths' last component then (does not work on Windows):
echo basename(parse_url($url, PHP_URL_PATH)),
'?',
parse_url($url, PHP_URL_QUERY),
"\n"
;
https://php.net/parse_url
https://php.net/preg_replace
https://www.php.net/manual/en/regexp.reference.assertions.php

Using preg_replace on url variables

I have some very long URL variables. Here is one example.
http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Ultimately it would be nice if I could find a way to use preg_replace to simply change one variable even if in the middle of the string for instance in the string above change print=no to 'print=yes for example.
I will however settle for a preg_replace pattern match that allows me to delete ?image=XYZ_1555025022.jpg. as this is a variable the name could be anything. It will always have "?image" " at the start and end with "&"
I think one of the problems I have run into is that preg_match seems to have issues on strings with "=" contained in them .
I am completely lost here in this and all those characters make may head spin. Maybe someone can give some guidance please?
Here's a demo of how you can do some of things you want using explode, parse_str and http_build_query:
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
// split on first ?
list($path, $query_string) = explode('?', $url, 2);
// parse the query string
parse_str($query_string, $params);
// delete image param
unset($params['image']);
// change the print param
$params['print'] = 'yes';
// rebuild the query
$query_string = http_build_query($params);
// reassemble the URL
$url = $path . '?' . $query_string;
echo $url;
Output:
http://localhost/index.php?mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=yes&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Demo on 3v4l.org
You can use str_replace() or preg_replace() to get your job done, but parse_url() with parse_str() will give you more controls to modify any parameters easily by array index. Finally use http_build_query() to make your final url after modification.
<?php
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo "BEFORE".PHP_EOL;
print_r($query);
$query['print'] = 'yes';
echo "AFTER".PHP_EOL;
print_r($query);
?>
DEMO: https://3v4l.org/npGij

How to remove two same and random characters following each other in string - PHP

Need to remove random aa/ or bb/ to zz/ letters (with slash) to get /logo/picture.png
$url = "/logo/aa/picture.png";
$url = "/logo/bb/picture.png";
$url = "/logo/cc/picture.png";
This is an alternative which doesn't care what's contained in that url part or what lengths url parts have:
$urlParts = explode('/', $url);
array_splice($urlParts, count($urlParts) - 2, 1);
$url = implode('/', $urlParts);
If the $url is always of the form you provided you could do:
$str1 = substr($url,0,5);
$str2 = substr($url,8,strlen($url));
$url = $str1.$str2;
if it's not always of the same form you could determine the substrings indexes programmatically, maybe using strpos function. More detail here
Luca Angioloni solution is correct but this is more stable:
$url preg_replace("/\/[a-z]{2}\//", "/", $url);
This will work even on url like: /img/xz/picture.png but if you have an url like this /ig/aa/picture.png this will remove /ig and not /aa

Remove characters from end of URL

Say I have a URL with something like this:
http://website.com/website/webpage/?message=newexpense
I have the following code to try and get the the URL before the question mark:
$post_url = $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$link_before_question_mark = explode('?', $actual_link);
$add_income_url = $link_before_question_mark[0];
In this example I would get the following URL:
http://website.com/website/webpage/
I'd like to remove the webpage portion of this so the URL is:
http://website.com/website/
How can I do this?
Use parse_url This way you have all components.
$url = 'http://website.com/website/webpage/?message=newexpense';
$pUrl = parse_url( $url);
echo $pUrl['scheme'] . '://' . $pUrl['host'] . $pUrl['path'];
You can do a similar trick using explode. Then pop the parts you don't need and implode the url back together. If you are sure that the part after '?' never contains a '/', you can replace your code with this one. If you're not sure, you should first remove the part after '/' and then run this code to remove the last part of the path.
<?php
$url = 'http://website.com/website/webpage/?message=newexpense';
$parts = explode('/', $url);
// Remove the last part from the array
$lastpart = array_pop($parts);
// If the last part is empty, or the last part starts with a '?'
// this means there was a '/' at the end of the url, so we
// need to pop another part.
if ($lastpart == '' or substr($lastpart, 0, 1) == '?')
array_pop($parts);
$url = implode('/', $parts);
var_dump($url);
I'd probably use dirname; it's specifically designed to strip the last stuff after a "/"...
$url = "http://website.com/website/webpage/?message=newexpense";
echo dirname(dirname($url))."/"; // "http://website.com/website/"
(As it says in the documentation, "dirname() operates naively on the input string, and is not aware of the actual filesystem...", so it's quite safe to use for this kind of purpose.)
Try it with explode
<?php
$actual_link = "http://website.com/website/webpage/?message=newexpense]";
$link_before_question_mark = explode('?', $actual_link);
$add_income_url = $link_before_question_mark[0];
$split=explode('/', $add_income_url);
echo $split[0]."//".$split[2]."/".$split[3]."/";
?>
Even better is...
<?php
$actual_link = "http://website.com/website/webpage/?message=newexpense]";
$split=explode('/', $actual_link);
echo $split[0]."//".$split[2]."/".$split[3]."/";
?>

php : Retrieving number in the URL

I have url in the following types
http://domain.com/1/index.php
http://domain.com/2/index.php
http://domain.com/3/index.php
http://domain.com/4/index.php
I need to retrieve only the number from the url .
for example,
when i visit http://domain.com/1/index.php , It must return 1.
Have a look at parse_url.
$url = parse_url('http://domain.com/1/index.php');
EDIT: Take a look at $_SERVER['REQUEST_URI'], to get the current URL. Use that instead of $url['path'].
Then you can split $url['path'] on /, and get the 1st element.
// use trim to remove the starting slash in 'path'
$path = explode('/', trim($url['path'], '/'));
$id = $path[0]; // 1
Given the information provided, this will do what you ask... it's not what I would call a robust solution:
$url = $_SERVER['PATH_INFO']; // e.g.: "http://domain.com/1/index.php";
$pieces = explode("/", $url);
$num = $pieces[3];
split the server path by forward slashes (explode('/', $_SERVER['REQUEST_PATH']);)
remove empty entry from the beginning
take the first element
make sure it is an integer (intval(), or a simple (int) cast).
No need to use regular expressions for this.
You use preg_match() to match the domain and get the 1st segment.
$domain = http://www.domain.com/1/test.html
preg_match("/http:\/\/.*\/(.*)\/.*/", "http://www.domain.com/1/test.html");
echo $matches[1]; // returns the number 1 in this example.

Categories