I would like to know how I can cut a string in PHP starting from the last character -> to a specific character. Lets say I have following link:
www.whatever.com/url/otherurl/2535834
and I want to get 2535834
Important note: the number can have a different length, which is why I want to cut out to the / no matter how many numbers there are.
Thanks
In this special case, an url, use basename() :
echo basename('www.whatever.com/url/otherurl/2535834');
A more general solution would be preg_replace(), like this:
<----- the delimiter which separates the search string from the remaining part of the string
echo preg_replace('#.*/#', '', $url);
The pattern '#.*/#' makes usage of the default greediness of the PCRE regex engine - meaning it will match as many chars as possible and will therefore consume /abc/123/xyz/ instead of just /abc/ when matching the pattern.
Use
explode() AND end()
<?php
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo end ($tmp);
?>
Working Demo
This should work for you:
(So you can get the number with or without a slash, if you need that)
<?php
$url = "www.whatever.com/url/otherurl/2535834";
preg_match("/\/(\d+)$/",$url,$matches);
print_r($matches);
?>
Output:
Array ( [0] => /2535834 [1] => 2535834 )
With strstr() and str_replace() in action
$str = 'www.whatever.com/url/otherurl/2535834';
echo str_replace("otherurl/", "", strstr($str, "otherurl/"));
strstr() finds everything (including the needle) after the needle and the needle gets replaced by "" using str_replace()
if your pattern is fixed you can always do:
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo $temp[3];
Here's mine version:
$string = "www.whatever.com/url/otherurl/2535834";
echo substr($string, strrpos($string, "/") + 1, strlen($string));
Related
Have a url kind of this
https://example.com.ua/part1/part2/part3/product-123.html
How to get product-123.html with regular expression?
I tried this:
echo
preg_replace('#/([a-zA-Z0-9_-]+\.html)$#','$1','https://example.com.ua/part1/part2/part3/product-123.html');
You don't need regular expression for that
There's more than one way of doing it.
Look into parse_url().
parse_url(): This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
That will get you most of the way there and will also separate the host for you. Then you just explode your way to the last part using explode() and end().
$url = parse_url('http://example.com/project/controller/action/param1/param2');
$url['last'] = end(explode('/', $url[path]));
Array
(
[scheme] => http
[host] => example.com
[path] => /project/controller/action/param1/param2
[last] => param2
)
Or you can go straight to the point like this:
$last = ltrim(strrchr(parse_url($url, PHP_URL_PATH), '/'), '/');
You can also just go a head and use explode() in combination of end() directly on the URL. (it's also a lot shorter if you don't need the extra information of parse_url)
$last = end(explode('/', $url));
You can also just use basename() like this
$url = "http://example.com/project/controller/action/param1/param2";
$last = basename($url);
// Output: param2
The preg_replace only replaces what you have it find. In this case product-123.html. So you're replacing /product-123.html with product-123.html and the https://example.com.ua/part1/part2/part3 remains untouched.
To replace everything and only keep the match you'd do
echo
preg_replace('#.*/([a-zA-Z0-9_-]+\.html)$#','$1','https://example.com.ua/part1/part2/part3/product-123.html');
you don't need a regex though to accomplish this task, and if you did it'd probably be cleaner to use preg_match.
Here's a preg_match approach:
preg_match('#[a-zA-Z0-9_-]+\.html$#', 'https://example.com.ua/part1/part2/part3/product-123.html', $match);
echo $match[0];
Demo: https://3v4l.org/4o9RM
Regex demo: https://regex101.com/r/6dytu0/2/
Why regex?
$str ="https://example.com.ua/part1/part2/part3/product-123.html";
Echo Substr($str, strrpos($str, "/")+1);
https://3v4l.org/rJiGL
Strrpos finds the last / and returns position.
Here is a preg_replace that will work if you must use regex.
https://regex101.com/r/6zJwBo/1
$re = '/.*\//';
$str = 'https://example.com.ua/part1/part2/part3/product-123.html';
$subst = '';
$result = preg_replace($re, $subst, $str);
I couldn't find the solution using search.
I am looking for a php solution to remove all character BEFORE the second occurance of and underscore (including the underscore)
For example:
this_is_a_test
Should output as:
a_test
I currently have this code but it will remove everything after the first occurance:
preg_replace('/^[^_]*.s*/', '$1', 'this_is_a_test');
Using a slightly different approach,
$s='this_is_a_test';
echo implode('_', array_slice( explode( '_', $s ),2 ) );
/* outputs */
a_test
preg_replace('/^.*_.*_(.*)$/U', '$1', 'this_is_a_test');
Note the U modifier which tells regex to take as less characters for .* as possible.
You can also use explode, implode along with array_splice like as
$str = "this_is_a_test";
echo implode('_',array_splice(explode('_',$str),2));//a_test
Demo
Why go the complicated way? This is a suggestion though using strrpos and substr:
<?php
$str = "this_is_a_test";
$str_pos = strrpos($str, "_");
echo substr($str, $str_pos-1);
?>
Try this one.
<?php
$string = 'this_is_a_test';
$explode = explode('_', $string, 3);
echo $explode[2];
?>
Demo
I'm still in favor of a regular expression in this case:
preg_replace('/^.*?_.*?_/', '', 'this_is_a_test');
Or (which looks more complex here but is easily adjustable to N..M underscores):
preg_replace('/^(?:.*?_){2}/', '', 'this_is_a_test');
The use of the question mark in .*? makes the match non-greedy; and the pattern has been expanded from the original post to "match up through" the second underscore.
Since the goal is to remove text the matched portion is simply replaced with an empty string - there is no need for a capture group or to use such as the replacement value.
If the input doesn't include two underscores then nothing is removed; such can be adjusted, very easily with the second regular expression, if the rules are further clarified.
Using PHP I have an array that return this data for an image:
Array
(
[0] => http://website.dev/2014/05/my-file-name-here-710x557.png
[1] => 710
[2] => 557
[3] => 1
)
Based on the demo data above, I need to somehow turn this image URL into:
http://website.dev/2014/05/my-file-name-here.png removing the -710x557 from the string.
Some things to keep in mind are:
The file extension can change and be any type of file type
710x557 might not ALWAYS be a 3 digit x 3 digit number. It could be 2 or 4
The reason I mention this is to show I cannot simply use PHP's string functions to remove the last 12 characters in the string and then add the file extension back because the last string characters could possibly be between 10 and 14 characters long sometimes and not always 12.
I was hoping to avoid a heavy regular expression code but if that is the only or best way here then I say go with it.
How do I write a regex that removes the end of a string that could have a varying length in PHP?
You can use a regex like this:
-\d+x\d+(\.\w+)$
Working demo
The code you can use is:
$re = "/-\\d+x\\d+(\\.\\w+)$/";
$str = "http://website.dev/2014/05/my-file-name-here-710x557.png";
$subst = '\1';
$result = preg_replace($re, $subst, $str, 1);
The idea is to match the resolution -NumbersXNumbers using -\d+x\d+ (that we'll get rid of it) and then capture the file extension by using (\.\w+)$ using capturing group. Check the substitution section above.
As long as it is 2 sets of digits with an 'x' in the middle preceded by a dash you can use this regex:
-[\d]*x[\d]*
$string = 'http://website.dev/2014/05/my-file-name-here-710x557.png';
$pattern = '/-[\d]*x[\d]*/';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
http://phpfiddle.org/lite/code/eh40-6d1x
You can probably use strrpos in the following manner to do this:
$str = substr($str, 0, strrpos($str, '-')) . substr($str, strrpos($str, '.'));
You can use this regex based code:
$str = "http://website.dev/2014/05/my-file-name-here-710x557.png";
$re = '/-([^-]+)(?=\.[^-]*$)/';
$result = preg_replace($re, '', $str, 1);
//=> http://website.dev/2014/05/my-file-name-here.png
RegEx Demo
$newsrc = preg_replace('#\-\d+x\d+(\.\w+$)#', '$1', $arr[0]);
see http://ideone.com/ZsELQ0
I have a string that contains many underscores followed by words ex: "Field_4_txtbox" I need to find the last underscore in the string and remove everything following it(including the "_"), so it would return to me "Field_4" but I need this to work for different length ending strings. So I can't just trim a fixed length.
I know I can do an If statement that checks for certain endings like
if(strstr($key,'chkbox')) {
$string= rtrim($key, '_chkbox');
}
but I would like to do this in one go with a regex pattern, how can I accomplish this?
The matching regex would be:
/_[^_]*$/
Just replace that with '':
preg_replace( '/_[^_]*$/', '', your_string );
There is no need to use an extremly costly regex, a simple strrpos() would do the job:
$string=substr($key,0,strrpos($key,"_"));
strrpos — Find the position of the last occurrence of a substring in a string
You can also just use explode():
$string = 'Field_4_txtbox';
$temp = explode('_', strrev($string), 2);
$string = strrev($temp[1]);
echo $string;
As of PHP 5.4+
$string = 'Field_4_txtbox';
$string = strrev(explode('_', strrev($string), 2)[1]);
echo $string;
I have an alpha numeric string say for example,
abc123bcd , bdfnd567, dfd89ds.
I want to trim all the characters before the first appearance of any integer in the string.
My result should look like,
abc , bdfnd, dfd.
I am thinking of using substr. But not sure how to check for a string before first appearance of an integer.
You can easily remove the characters you don't want with preg_replace [docs] and a regular expression:
$str = preg_replace('#\d.*$#', '', $str);
\d matches a digit and .*$ matches any character until the end of the string.
Learn more about regular expressions: http://www.regular-expressions.info/.
DEMO
A possible non-Regex solution would be:
strcspn — Find length of initial segment not matching mask
substr — Return part of a string
Example:
$string = 'foo1bar';
echo substr($string, 0, strcspn($string, '1234567890')); // gives foo
$string = 'abc123bcd';
preg_replace("/[0-9]/", "", $string);
or
trim($string, '0123456789');
I believe you are looking for this?
$matches = array();
preg_match("/^[a-z]+/", "dfd89ds", $matches);
echo $matches[0]; // returns dfd
You can use a regex for this:
$string = 'abc123bcd';
preg_match('/^[a-zA-Z]*/i', $string, $matches);
var_dump($matches[0]);
will produce:
abc
To remove the +/- sign, you can simply use:
abs($number)
and get the absolute value.
e.g
$abs = abs($signed_integer);