Is there a way in php to do a preg_match on a url like below
dynamic/dynamic/dev/new_mobile/lib
and it would only pull out dev/new_mobile, and the link also has the ability to be like this too
dynamic/dynamic/dynamic/tst/new_mobile/lib
In the above example it would only pull out tst/new_mobile. The key is it would grab the last two directories before lib. Any idea how this could be done?
Here's a regex that will get the part you want:
$url = 'dynamic/tst/new_mobile/lib/foo/bar';
if (preg_match('#^(?:.*?/)?([^/]+/[^/]+)/lib(?:/.+)?$#', $url, $matches)) {
$part = $matches[1];
var_dump($part); // "tst/new_mobile"
}
This will get the 2 directories before the lib directory allowing for any directories before and after. It will also match a couple of edge cases that you don't mention whether you need:
tst/new_mobile/lib/foo/bar
/tst/new_mobile/lib/foo/bar
just explode then reverse array, simple and easy to use.
$array_url = explode('/',$url);
$tmp_array_url = array_reverse($array_url);
then you can rebuild as you will, no need to wonder with how many dynamic parts come before.
echo $tmp_array_url[0]; // "lib";
echo $tmp_array_url[1]; // "new_mobile";
echo $tmp_array_url[2]; // "dev";
EDIT: since you got lib constant, just do something like this :
$the_two_before = "";
for($i = 0; $i < count($tmp_array_url); $i++){
if($tmp_array_url[$i] == "lib"){
$the_two_before = $tmp_array_url[$i+2]."/".$tmp_array_url[$i+1];
}
}
Related
I have a string localhost/uploads/images/photo.jpg, I just want to simply rename it to localhost/upload/images/photo_thumb.jpg, keeping in mind that is a dynamic data and am just using it to simply what I want to achieve. I have tried to use the strpos() function to get the position of the '.' then use it for something(this where I got lost), then another thought came to me use implode. I will appreciate if some can help me figure this out thanks.
<?php
function get_google_image_url($type, $id, $column = 'image', $multi = "",$thumb=''){
if($multi ==''){
//check if there is thumbnail add _thumb before extention
if($thumb != ''){
$l= $this->db->get_where($type,array($type.'_id'=>$id));
$n = $l->num_rows();
if($n >0){
$value = $l->row()->$column;
$position = strripos($value,'.');
return $l->row()->$column;
}
}else{
$l= $this->db->get_where($type,array($type.'_id'=>$id));
$n = $l->num_rows();
if($n >0){
/$value = $l->row()->$column
$position = strripos($value,'.');
//this where i got stucked
//return $l->row()->$column;
}
}
}
}
that's the function am trying to implement it in, but what I want to achieve is what I stated above.
i think the best way here is to use pathinfo
something like that should work
$path_parts = pathinfo('localhost/uploads/images/photo.jpg');
$strNewName = $path_parts['dirname'].'/photo_thumb.jpg';
echo $strNewName;
I would do it by using regex and preg_replace:
$string="localhost/uploads/images/photo_thumb.jpg";
$replacement="$1/$2_thumb.$3";
$pattern= '/([\w+\/]*)(?=\/)\/([\w]+(?<!_thumb))\.(\w+)/i';
echo preg_replace($pattern, $replacement, $string);
code you can run it here
$1 = matching until last /
$2 = name of the file
$3 = file extension
feel free to improve the regex pattern if needed.
I have a string with html code. It has lot of urls formats. I used preg_match_all to get all the urls. Now i want to loop through $match2 array and only print the urls that has ".m3u8" some where in the full url. var_dump($match2) prints all the urls correctly but my for loop keep giving me this error;
E_NOTICE : type 8 -- Array to string conversion
could any one help me fix this problem ?Thanks in advance.
php code:
$regex2 = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i";
preg_match_all($regex2,$code,$match2);
var_dump($match2);
for($i = 0; $i < count($match2); $i++){
if (strpos($match2[$i],'.m3u8') !== false) {
echo "<br>".$match2[$i];
} else {
//do nothing
}
}
I changed $match2 to $match2[0] and it wroked!
I want to add some html to a word based on the words in a compound word.
For instance let's take the word "doghouse'
Let's say
$row2['word'] = 'doghouse';
$word = 'dog';
$otherword = 'house';
I want the end result to produce
<span style="color:blue">dog</span><span style="color:red">house</span>
My code so far that does not work (which I thought I could array the replace in str_replace but apparently I can't.
$finalword = str_replace(array($word,$otherword),array("<span style='color:blue'>".$word."</span>","<span style='color:red'>".$word."</span>"),$row2['word']);
Is str_replace the wrong choice for this?
str_replace is the correct function, but you're not really using it correctly. The way you've set it up, $row2 would have to be an array, but it's not, it's a string. So you need to use an alternate approach. Your code should look like this:
str_replace($row2, $word.$otherword, "<span style='color:blue'>".$word."</span><span style='color:red'>".$otherword."</span>");
The first term ($row2) is where you're searching, what php calls the 'haystack'. The second term $word.$otherword is what you're searching for (the 'needle'). The third term is what you replace the 'needle' with when you find it.
I don't know how do you store your colors, but does it work for you?
$row2['word'] = 'doghouse';
$words = array('dog','house');
$colors = array('blue', 'red');
$finalword = "";
for ($i = 0; $i < count($words); $i++) {
$finalword .= "<span style='color:".$colors[$i]."'>".$words[$i]."</span>";
}
echo $finalword;
Hi guys i m using this code to get the id on my url
$string = $url;
$matches = array();
preg_match_all('/.*?\/(\d+)\/?/s', $string, $matches);
$id = $matches[1][0];
this code works for urls like
http://mysite.com/page/1
http://mysite.com/page/somepage/2
http://mysite.com/page/3/?pag=1
i will have id = 1 / id = 2 / id = 3
but for a url like this
http://mysite.com/page/122-page-name/1
this returns id = 122
THe id i m try to get always will be the last part of the url or will have /?p= after
so the urls type i can have
http://mysite.com/page/1
http://mysite.com/page/some-page/2
http://mysite.com/page/12-some-name/3
http://mysite.com/page/some-page/4/?p=1
http://mysite.com/page/13-some-page/5/?p=2
id = 1 / id = 2 / id = 3 / id = 4 / id = 5
If your id will always be located at the end of your url, you could explode the contents of your url and take the last element of the resulting array. If it may include variables (like ?pag=1) you can add a validation after the explode to check for the variable.
$urlArray = explode('/', $url);
$page = end($urlArray);
if(strpos($page, 'pag')!==false){
//get the contents of the variable from the $page variable
//exploding the variable through the ? variable and getting
//the numeric characters at the end
}
I would favor URL parsing over trying to use a regex, especially if you have a wide variety of (valid) URLs to deal with.
end(array_filter(explode('/', parse_url($url, PHP_URL_PATH))));
The array_filter deals with the trailng slash.
Since it's always at the end or has ?p=x after it you can do the following:
$params = explode('/', $_SERVER['REQUEST_URI']);
$c = count($params);
if (is_int($params[$c - 1])
$id = $params[$c - 1];
else
$id = $params[$c - 2];
Not a direct answer, more of a "how to work this out for yourself" answer :]
Place this code at the top of your page, before anything else (but after <?php)
foreach($_SERVER as $k => $v) {
echo $k.' = '.$v.'<br />';
}
exit;
Now load up each of the different URIs in a different tab and look at the results. You should be able to work out what you need to do.
I am parsing domains and running into a problem handling subdomains. If the domain is http://www.google.co.uk, I want to obtain the length of google which is 6.
I am using parse_url() to return the host in this case www.google.co.uk like so.
$url = 'http://www.google.co.uk';
$info = parse_url($url);
// remove www. and return google.co.uk
$new = str_replace('www.','',$info['host']);
$pieces = explode(".", $new);
$len = strlen($pieces[0]); // returns character length of google = 6
echo $len;
My code doesn't work if the domain contains a subdomain like http://test.google.co.uk: it returns a length of 4; I expect it to return a length of 6.
Any ideas?
Output is correct. when input is http://test.google.co.uk value of parse_url('http://test.google.co.uk')['host'] is http://test.google.co.uk. When you will exploce this string on dot first element of array will be test and its length is 4.
To get google instead of test you need to replace subdomain with nothing as you did in your first example or take the second element in exploded string. E.g:
$url = 'http://test.google.co.uk';
$info = parse_url($url);
$pieces = explode(".", $info['host']);
$len = strlen($pieces[1]); // returns character length of google = 6
echo $len;
There is not other way than collect and hardcode all known public 2-nd level zones (like co.uk, com.ua, co.tw and so on) and filter them in your code. Be aware to detect test.example.ua as test becouse both example.com.ua and example.ua are valid domains (which is not a case with uk zone).
Your code may look like this:
function mainDomainLength($fullDomain) {
//$fullDomain = 'DOMAIN.co.uk';
$zones = array('uk' => array('co'), 'ua' => array('com', 'org'), ...);
$domainArray = explode('.', $fullDomain);
if (count($domain) > 2 && isset($zones[$domain[count($domain)-1]])) {
if (isset($zones[$domain[count($domain)-1]][$domain[count($domain)-2]])) {
return strlen($domain[count($domain)-3]);
}
} else if (count($domain) > 1) {
return strlen($domain[1]);
} else {
return strlen($domain[0]);
}
}
EDIT: By the way! Look at Get the second level domain of an URL (java). As I can understand there is the answer you need (and url to special domains collection collected be Mozilla).