Regex - number from string which is not 1 - php

Need a regex to get numbers of pages in the thread:
example url : traidnt.net/vb/f25
i tried this :
'~<td class="vbmenu_control" style="font-weight:normal">.*([2-9]{1}|[0-9]{2,}).*</td>~isU'
but it wont work.
Thanking you

/.*?([0-9]{2,}|[2-9]{1}).*/s
matches a one-digit number > 1 or any multi-digit number.
please note that this does not match correctly when: "page 1 of 1 pages"
if the string is fixed, you better go with:
/page \d+ of (\d+) pages/is
or if the string is not absolutely fixed but you want the second number from the string you may use:
/\D*(\d+)\D*(\d+)\D*/s
and use the second sub-match. (will also match correctly when "page 1 of 1 pages".

You can use \d+ to match numbers, and a negative assertion (?!...) to exclude something. Often you need some anchors around to make it work reliably, here word boundaries:
/\b(?!1\b)\d+\b/

This will find all digits, which are not one:
/[^\D1]/

<?php
$str="page 1 of 200 pages";
$matches = array();
if (preg_match('/page (\d+) of (\d+)/', $str, $matches)) {
echo $matches[2];
}
?>
for the updated question:
$url="traidnt.net/vb/f25";
$matches1 = array();
if (preg_match('/f(\d+)/', $url, $matches1)) {
echo $matches1[1];
}
?>

Related

Removing all characters and numbers except last variable with dash symbol

Hi I want to remove a characters using preg_replace in php so i have this code here which i want to remove the whole characters, letters and numbers except the last digit(s) which has dash(-) symbol followed by a digits so here's my code.
echo preg_replace('/(.+)(?=-[0-9])|(.+)/','','asdf1245-10');
I expect the result will be
-10
the problem is above is not working very well. I checked the pattern using http://www.regextester.com/ it seems like it works, but on the other side http://www.phpliveregex.com/ doesn't work at all. I don't know why but anyone who can help to to figure it out?
Thanks a lot
Here is a way to go:
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf1245-10');
Output:
-10
and
echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf124510');
Output:
<nothing>
My first thinking is to use explode in this case.. make it simple like the following code.
$string = 'asdf1245-10';
$array = explode('-', $string);
end($array);
$key = key($array);
$result = '-' . $array[$key];
$result => '-10';
An other way:
$result = preg_match('~\A.*\K-\d+\z~', $str, $m) ? $m[0] : '';
pattern details:
\A # start of the string anchor
.* # zero or more characters
\K # discard all on the left from match result
-\d+ # the dash and the digits
\z # end of the string anchor
echo preg_replace('/(\w+)(-\w+)/','$2', 'asdf1245-10');

Make two simple regex's into one

I am trying to make a regex that will look behind .txt and then behind the "-" and get the first digit .... in the example, it would be a 1.
$record_pattern = '/.txt.+/';
preg_match($record_pattern, $decklist, $record);
print_r($record);
.txt?n=chihoi%20%283-1%29
I want to write this as one expression but can only seem to do it as two. This is the first time working with regex's.
You can use this:
$record_pattern = '/\.txt.+-(\d)/';
Now, the first group contains what you want.
Your regex would be,
\.txt[^-]*-\K\d
You don't need for any groups. It just matches from the .txt and upto the literal -. Because of \K in our regex, it discards the previously matched characters. In our case it discards .txt?n=chihoi%20%283- string. Then it starts matching again the first digit which was just after to -
DEMO
Your PHP code would be,
<?php
$mystring = ".txt?n=chihoi%20%283-1%29";
$regex = '~\.txt[^-]*-\K\d~';
if (preg_match($regex, $mystring, $m)) {
$yourmatch = $m[0];
echo $yourmatch;
}
?> //=> 1

Avoid regex match if pattern has string before it

I have these strings, and I want to match b=(\d+) only not ab=(\d+). How do I do it?
"ab=10&b=20" -> 20
"b=20&ab=10" -> 20
"b=20" -> 20
"ab=10" -> no match
You could use \b, like:
\bb=(\d+)
Which matches only at a word boundary (between a \w and not a \w).
Use a negative lookbehind:
/(?<!a)b=(\d+)/
Now this will match any number followed by b= if not preceded by the character a.
Test case:
$array = array(
"ab=10&b=20",
"b=20&ab=10",
"b=20",
"ab=10"
);
foreach ($array as $str) {
if (preg_match('/(?<!a)b=(\d+)/', $str, $matches)) {
echo $matches[1], PHP_EOL;
} else {
echo "No match", PHP_EOL;
}
}
Output:
20
20
20
No match
Demo
This is what I got:
(?:[^a-zA-Z])(?:b=(\d+))
(?:[^a-zA-Z]) It can not start with a-Z. You might want to change this, but you get the idea
(?:b=(\d+)) I wrapped it in a group to make the regex combine it, ?: makes sure \\1 will still be 20

php expressions preg_match

I have been trying to figure this out really hard and I cannot came out with a solution ,
I have an arrary of strings which is
"Descripcion 1","Description 2"
and I need to filter by numbers, so I thought maybe I can use preg_match() and find when there is exactly 1 number 1 or two or etc, and do my logic, becouse the string before the number may change, but the number cannot, I have tried using
preg_match(" 1{1}","Description 1")
which is suppossed to return true when finds an space followed by the string "1" exactly one time but returns false.
Maybe some of you have had more experience with regular expressions in php and can help me.
Thank you very much in advance.
You could use strpos instead of preg_match!
foreach($array as $string) {
if(strpos($string, ' 1') !== false) {
//String contains " 1"!!
}
}
This would be much faster then a regular expression.
Or, if the Number has to be at the end of the string:
foreach($array as $string) {
if(substr($string, -2) == ' 1') {
//String ends with " 1"!!
}
}
You forgot the regex delimiters. Use preg_match('/ 1/', ...) instead.
However, you do not need a regex at all if you just want to test if a string is contained within another string! See Lars Ebert's answer.
You might have success using
if (preg_match('/(.*\s[1])/', $var, $array)) {
$descrip = $array[1];
} else {
$descrip = "";
}
I tested the above regex on the 3 separate string values of descripcion 1, thisIsAnother 1, andOneMore 1. Each were found to be true by the expression and were saved into group 1.
The explanation of the regex code is:
() Match the regular expression between the parentheses and capture the match into backreference number 1.
.* Match any single character that is not a line break character between zero and as many times possible (greedy)
\s Match a single whitespace character (space, tab, line break)
[1] Match the character 1

Extract last section of string

I have a string like this:
[numbers]firstword[numbers]mytargetstring
I would like to know how is it possible to extract "targetstring" taking account the following :
a.) Numbers are numerical digits for example, my complete string with numbers:
12firstword21mytargetstring
b.) Numbers can be any digits, for example above are two digits each, but it can be any number of digits like this:
123firstword21567mytargetstring
Regardless of the number of digits, I am only interested in extracting "mytargetstring".
By the way "firstword" is fixed and will not change with any combination.
I am not very good in Regex so I appreciate someone with strong background can suggest how to do this using PHP. Thank you so much.
This will do it (or should do)
$input = '12firstword21mytargetstring';
preg_match('/\d+\w+\d+(\w+)$/', $input, $matches);
echo $matches[1]; // mytargetstring
It breaks down as
\d+\w+\d+(\w+)$
\d+ - One or more numbers
\w+ - followed by 1 or more word characters
\d+ - followed by 1 or more numbers
(\w+)$ - followed by 1 or more word characters that end the string. The brackets mark this as a group you want to extract
preg_match("/[0-9]+[a-z]+[0-9]+([a-z]+)/i", $your_string, $matches);
print_r($matches);
You can do it with preg_match and pattern syntax.
$string ='2firstword21mytargetstring';
if (preg_match ('/\d(\D*)$/', $string, $match)){
// ^ -- end of string
// ^ -- 0 or more
// ^^ -- any non digit character
// ^^ -- any digit character
var_dump($match[1]);}
Try it like,
print_r(preg_split('/\d+/i', "12firstword21mytargetstring"));
echo '<br/>';
echo 'Final string is: '.end(preg_split('/\d+/i', "12firstword21mytargetstring"));
Tested on http://writecodeonline.com/php/
You don't need regex for that:
for ($i=strlen($string)-1; $i; $i--) {
if (is_numeric($string[$i])) break;
}
$extracted_string = substr($string, $i+1);
Above it's probably the faster implementation you can get, certainly faster than using regex, which you don't need for this simple case.
See the working demo
your simple solution is here :-
$keywords = preg_split("/[\d,]+/", "hypertext123language2434programming");
echo($keywords[2]);

Categories