php pattern matching - php

I want to get the part of the string before the last occurance of "-",
for example,
$string1 = 'a-b-c-de-f-gfgh';
I want to get this part returned: a-b-c-de-f. Of course, I don't know the length of the last part.
What is the easy way to do it?
Thank you

echo substr ($string1, 0, strrpos ($string1, '-'));
strrpos() finds the last occurrence of a substring, - in this case, and substr() splits the original string from the 0th character until the nth character as defined by strrpos()

Use strrpos() to get position of last "-" and substr() it:
echo substr($string1, 0, strrpos($string1, "-"));

get the last occurrence of - using $x = strrpos($string1,'-');
then use substr() to return the decired string from 0 to $x
echo substr ($string1, 0, $x);

You could remove that last part:
$string = preg_replace("|-[^-]+$|", "", $string);

As an alternative to the other posters:
preg_match('/(.*)-[^-]+/', 'a-b-c-de-f-gfgh', $result);
Result:
Array
(
[0] => a-b-c-de-f-gfgh-a
[1] => a-b-c-de-f-gfgh
)
Though I like Jeroens solution more.

Related

Cut string from end to specific char in php

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

php: split string until first occurance of a number

i have string like
cream 100G
sup 5mg Children
i want to split it before the first occurrence of a digit. so the result should be
array(
array('cream','100G'),
array('sup','5mg Children')
);
can so one tell me how to create pattern for this ?
i tried
list($before, $after) = array_filter(array_map('trim',
preg_split('/\b(\d+)\b/', $t->formula)), 'strlen');
but something went wrong.
Try this:
<?php
$first_string = "abc2 2mg";
print_r( preg_split('/(?=\d)/', $first_string, 2));
?>
Will output:
Array ( [0] => abc [1] => 2 2mg )
The regular expression solution would be to call preg_split as
preg_split('/(?=\d)/', $t->formula, 2)
The main point here is that you do not consume the digit used as the split delimiter by using positive lookahead instead of capturing it (so that it remains in $after) and that we ensure the split produces no more than two pieces by using the third argument.
You don't need regular expressions for that:
$str = 'cream 100g';
$p = strcspn($str, '0123456789');
$before = substr($str, 0, $p);
$after = substr($str, $p);
echo "before: $before, after: $after";
See also: strcspn()
Returns the length of the initial segment of $str which does not contain any of the characters in '0123456789', aka digits.

Trim all characters before an integer in a string in PHP?

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

Get first string before separator?

I have strings with folowing structure:
7_string_12
7_string2_122
7_string3_1223
How I can get string before second "_" ?
I want my final result to be :
7_string
7_string2
7_string3
I am using explode('_', $string) and combine first two values, but my script was very slow!
$str = '7_string_12';
echo substr($str,0,strrpos($str,'_'));
echoes
7_string
no matter what's at the begining of the string
If it always starts with 7_ you can try this:
$string = substr($text, 0, strpos($text, '_', 2));
The strpos() searches for the first _ starting from character 3 (= s from string). Then you use substr() to select the whole string starting from the first character to the character returned by strpos().
$s1 = '7_string_12';
echo substr($s1, 0, strpos($s1, '_', 2));

Delete first 3 characters and last 3 characters from String PHP

I need to delete the first 3 letters of a string and the last 3 letters of a string. I know I can use substr() to start at a certain character but if I need to strip both first and last characters i'm not sure if I can actually use this. Any suggestions?
Pass a negative value as the length argument (the 3rd argument) to substr(), like:
$result = substr($string, 3, -3);
So this:
<?php
$string = "Sean Bright";
$string = substr($string, 3, -3);
echo $string;
?>
Outputs:
n Bri
Use
substr($var,1,-1)
this will always get first and last without having to use strlen.
Example:
<?php
$input = ",a,b,d,e,f,";
$output = substr($input, 1, -1);
echo $output;
?>
Output:
a,b,d,e,f
As stated in other answers you can use one of the following functions to reach your goal:
substr($string, 3,
-3) removes 3 chars from start and end
trim($string, ",") removes all specific chars from start and end
ltrim($string, ".") removes all specific chars from start
rtrim($string, ";") removes all specific chars from end
It depends on the amount of chars you need to remove and if the removal needs to be specific. But finally substr() answers your question perfectly.
Maybe someone thinks about removing the first/last char through string dereferencing. Forget that, it will not work as null is a char as well:
<?php
$string = 'Stackoverflow';
var_dump($string);
$string[0] = null;
var_dump($string);
$string[0] = null;
var_dump($string);
echo ord($string[0]) . PHP_EOL;
$string[1] = '';
var_dump($string);
echo ord($string[1]) . PHP_EOL;
?>
returns:
string(13) "Stackoverflow"
string(13) "tackoverflow"
string(13) "tackoverflow"
0
string(13) "ackoverflow"
0
And it is not possible to use unset($string[0]) for strings:
Fatal error: Cannot unset string offsets in /usr/www/***.php on line **
substr($string, 3, strlen($string) - 6)
I don't know php, but can't you take the length of the string, start as position 3 and take length-6 characters using substr?
$myString='123456789';
$newString=substr($myString,3,-3);

Categories