PHP print only some part of the string - php

I have few PHP strings ($url1, $url2, ..) as below:
$url1 = "http://build:f9280396f83a0#mobile.com:8080/job/new-ios-2.1/buildWithParameters";
$url2 = "http://build:f9280396f83a0#mobile.com:8080/job/new-android-8.2/buildWithParameters";
How do I get the substring after /job/ and before /buildWithParameters? Here is the expected output for $url1:
new-ios-2.1
So far I have tried using substr function:
For example, $url1 = substr($url, -10);. I am not able to find the above desired job part by this approach. Is there a better way to do this in PHP?

You Can use explode function . 4th key's value will be as per your expectation
$url1 = "http://build:f9280396f83a0#mobile.com:8080/job/new-ios-2.1/buildWithParameters";
$urlarr=explode('/', $url1);
print_r($urlarr);

Use this regex:
preg_match('/\/job\/([^\/]*)\/buildWithParameters/', $url1, $matches);
print_r($matches[1]);
This will match the string between first occurrence of /job/ and first occurence of /buildWithParameters/
Check the demo here

Related

SPLIT URL in PHP

I have below URL in my code and i want to split it and get the number from it
For example from the below URL need to fetch 123456
https://review-test.com/#/c/123456/
I have tried this and it is not working
$completeURL = https://review-test.com/#/c/123456/ ;
list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));
Use parse_url
It's specifically made for this sort of thing.
You can do this without using regex also -
$completeURL = 'https://review-test.com/#/c/123456/' ;
list($url, $number) = explode('#c', str_replace('/', '', $completeURL));
echo $number;
If you wan to get the /c/123456/ params you will need to execute the following:
$url = 'https://review-test.com/#/c/123456/';
$url_fragment = parse_url($url, PHP_URL_FRAGMENT);
$fragments = explode('/', $url_fragment);
$fragments = array_filter(array_map('trim', $fragments));
$fragments = array_values($fragments);
The PHP_URL_FRAGMENT will return a component of the url after #
After parse_url you will end up with a string like this: '/c/123456/'
The explode('/', $url_fragment); function will return an array with empty indexes where '/' was extracted
In order to remove empty indexes array_filter($fragments); the
array_map with trim option will remove excess spaces. It does not
apply in this case but in real case scenario you better trim.
Now if you var_dump the result you can see that the array needs to
be reindexed array_values($fragments)
You should try this: basename
basename — Returns trailing name component of path
<?php
echo basename("https://review-test.com/#/c/123456/");
?>
Demo : http://codepad.org/9Ah83qaP
Subsequently you can directly take from pure regex to fetch numbers from string,
preg_match('!\d+!', "https://review-test.com/#/c/123456/", $matches);
print_r($matches);
Working demo
Simply:
$tmp = explode( '/', $completeUrl).end();
It will explode the string by '/' and take the last element
If you have no other option than regex, for your example data you could use preg_match to split your url instead of preg_replace.
An approach could be to
Capture the first part as a group (.+\/)
Then capture your number as a group (\d+)
Followed by a forward slash at the end of the line \/$/
This will take the last number from the url followed by a forward slash.
Then you could use list and skip the first item of the $matches array because that will contain the text that matched the full pattern.
$completeURL = "https://review-test.com/#/c/123456/";
preg_match('/(.+\/)(\d+)\/$/', $completeURL, $matches);
list(, $url, $number) = $matches;

How to get last part of a string?

I have this string:
"application/controllers/backend"
I want get:
backend
of course the backend it's dynamic, so could be change, so I'm looking for a solution that allow me to get only the last part of the string. How I can do that?
You can take the advantage of basename() to get the last part
in your case, it will be
basename("application/controllers/backend");
Output:
backend
Some thing like this :
echo end(explode("/", $url));
If this thorws error then do :
$parts = explode("/", $url);
echo end($parts);
$arr = explode ("/", $string);
//$arr[2] is your third element in the string
http://php.net/manual/en/function.explode.php
Just use
basename("application/controllers/backend");
http://php.net/manual/en/function.basename.php
And, if you want to do it with a regex:
$result = (preg_match('%.*[/\\\\](.*?)$%', $url, $regs)) ? $regs[1] : '';
You did ask initially for a solution with regex, so, although the other answers haven't involved regex, here is one approach which does.
You can use preg_match and str_replace for this:
$string = '"application/controllers/backend"';
preg_match('/[^\/]+"/', $string, $matches);
$last_item = str_replace('"','',$matches[0]);
$last_item is now a string containing the word backend.

Grab a word in a complex url by php

Hi I have this url where i want to grab the last word (oath2_access_token) after the equals sign by PHP where the last word can be anything not just oath2_acc..
https://api.linkedin.com/v1/peoplesearch:(facets:(code,buckets:(code,name,count)))?facets=industry,network&facet=industry,12&facet=network,F&oauth2_access_token=oath2_access_token
Please help to grab the word or atleast provide me the resources where i could learn and do it myself.
Thanks.
You can use explode to get all the values after the equal signs and then just get the last element of the array:
<?php
$url = 'https://api.linkedin.com/v1/peoplesearch:(facets:(code,buckets:(code,name,count)))?facets=industry,network&facet=industry,12&facet=network,F&oauth2_access_token=oath2_access_token';
$array = explode('=', $url);
$value = end(array_values($array));
echo $value;
?>
GET
(As others have pointed out) I'm not sure why you can't simply use this...
$token = $_GET['oauth2_access_token'];
http://php.net/_get
Regex
Seeing as you have tagged this question with regex...
preg_match('/.*=(.*)/', $url, $matches);
$token = $matches[1];
.*= => Select everything up to and including the last = sign (because * is greedy)
(.*) => Select everything after the last = sign and capture it
http://php.net/preg_match
http://www.regular-expressions.info/
Explode
You could also split the url on the = sign and take the last index...
$url_array = explode('=', $url);
$token = end($url_array);
http://php.net/explode
http://php.net/end
preg_match("/oauth2_access_token\=([a-z0-9_\-]+)/i", $url, $matches);
I guess this pattern should cover the token, if not you'll need to define the allowed characters between the [] brackets.
Dump $matches to see which index grabs the token.
Either use
$_GET['oauth2_access_token']
or use parse_url. :
<?php
$url = "https://api.linkedin.com/v1/peoplesearch:(facets:(code,buckets:(code,name,count)))?facets=industry,network&facet=industry,12&facet=network,F&oauth2_access_token=oath2_access_token";
$querystring_params = array();
parse_str(parse_url($url, PHP_URL_QUERY), $querystring_params);
echo $querystring_params["oauth2_access_token"];
?>

Match unique string in PHP between common characters

I'm trying to do some string matching in PHP. I have the following url string in a variable:
phones/gift.nintendo-3ds/handset.blackberry-9790.html
I want remove the /gift.nintendo-3ds from the above, but the gift will always be different.
Any ideas? I want the url variable to look like this after each call different gifts:
phones/handset.blackberry-9790.html
Thanks
preg_replace('/\/gift\.[^/]*/', '', $url);
Matches /gift. then anything till the next slash and replaces it with blank.
Try with:
$input = 'phones/gift.nintendo-3ds/handset.blackberry-9790.html';
$output = preg_replace('(gift\.[^/]*\/)', '', $input);
You could split it apart, remove the second part you do not want to keep and then concat it again:
$parts = explode('/', $url, 3);
unset($parts[1]);
$result = implode('/', $parts);
This is not using any regular expression as you might have thought about but probably tells you about some other useful functions.
Demo: http://codepad.org/a1pNW8J6
A regex variant could be:
echo preg_replace('~^([^/]+)(/[^/]+)~', '$1', $url);
Demo: http://codepad.org/vyR04xMn

PHP preg_match between text and the first occurrence of -

I'm trying to grab the 12345 out of the following URL using preg_match.
$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";
$beg = "http://www.somesite.com/directory/";
$close = "\-";
preg_match("($beg(.*)$close)", $url, $matches);
I have tried multiple combinations of . * ? \b
Does anyone know how to extract 12345 out of the URL with preg_match?
Two things, first off, you need preg_quote and you also need delimiters. Using your construction method:
$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";
$beg = preg_quote("http://www.somesite.com/directory/", '/');
$close = preg_quote("-", '/');
preg_match("/($beg(.*?)$close)/", $url, $matches);
But, I would write the query slightly differently:
preg_match('/directory\/(\d+)-/i', $url, $match);
It only matches the directory part, is far more readable, and ensures that you only get digits back (no strings)
This doesn't use preg_match but would achieve the same thing and would execute faster:
$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";
$url_segments = explode("/", $url);
$last_segment = array_pop($url_segments);
list($id) = explode("-", $last_segment);
echo $id; // Prints 12345
Too slow, I am ^^.
Well, if you are not stuck on preg_match, here is a fast and readable alternative:
$num = (int)substr($url, strlen($beg));
(looking at your code I guessed, that the number you are looking for is a numeric id is it is typical for urls looking like that and will not be "12abc" or anything else.)

Categories