Get number from a string - php

I have a string for example "lorem 110 ipusm" and I want to get the 110
I already tried this:
preg_match_all("/[0-9]/", $string, $ret);
but this is returning this:
Array
(
[0] => 1
[1] => 1
[2] => 0
)
I want something like this
Array
(
[0] => 110
)

To catch any floating point number use:
preg_match_all("/[+-]?\d+[\d\.Ee+]*/", $string, $matches);
for example:
<?
$string = 'ill -1.1E+10 ipsum +1,200.00 asdf 3.14159, asdf';
preg_match_all("/[+-]?\d+[\d\.Ee+]*/", $string, $matches);
var_dump($matches);
?>
when run gives:
array(1) {
[0]=>
array(4) {
[0]=>
string(8) "-1.1E+10"
[1]=>
string(2) "+1"
[2]=>
string(6) "200.00"
[3]=>
string(7) "3.14159"
}
}

Use the + (1 or more match) operator:
preg_match_all("/[0-9]+/", $string, $ret);
Also, are you trying to support signs? decimal points? scientific notation? Regular expressions also support a shorthand for character classes; [0-9] is a digit, so you can simply use \d.

You have to mach more than one digit:
preg_match_all("/[0-9]+/", $string, $ret);

Use /\d+/ - that should solve it.

Related

How does one split a string on two delimeters into an associative array

The answer on this question, pointed me in a possible direction, but it processes the string once, then loops through the result. Is there a way to do it in one process?
My string is like this, but much longer:
954_adhesives
7_air fresheners
25_albums
236_stuffed_animial
819_antenna toppers
69_appliances
47_aprons
28_armbands
I'd like to split it on linebreaks, then on underscore so that the number before the underscore is the key and the phrase after the underscore is the value.
Just use a regular expression and array_combine:
preg_match_all('/^([0-9]+)_(.*)$/m', $input, $matches);
$result = array_combine($matches[1], array_map('trim', $matches[2]));
Sample output:
array(8) {
[954]=>
string(9) "adhesives"
[7]=>
string(14) "air fresheners"
[25]=>
string(6) "albums"
[236]=>
string(15) "stuffed_animial"
[819]=>
string(15) "antenna toppers"
[69]=>
string(10) "appliances"
[47]=>
string(6) "aprons"
[28]=>
string(8) "armbands"
}
Use ksort or arsort if you need the result sorted as well, by keys or values respectively.
You can do it in one line:
$result = preg_split('_|\n',$string);
Here is a handy-dandy tester: http://www.fullonrobotchubby.co.uk/random/preg_tester/preg_tester.php
EDIT:
For posterity, here's my solution. However, #Niels Keurentjes answer is more appropriate, as it matches a number at the beginning.
If you wanted to do this with regular expressions, you could do something like:
preg_match_all("/^(.*?)_(.*)$/m", $content, $matches);
Should do the trick.
If you want the result to be a nested array like this;
Array
(
[0] => Array
(
[0] => 954
[1] => adhesives
)
[1] => Array
(
[0] => 7
[1] => air fresheners
)
[2] => Array
(
[0] => 25
[1] => albums
)
)
then you could use an array_map eg;
$str =
"954_adhesives
7_air fresheners
25_albums";
$arr = array_map(
function($s) {return explode('_', $s);},
explode("\n", $str)
);
print_r($arr);
I've just used the first three lines of your string for brevity but the same function works ok on the whole string.

php regular expression: how to correctly escape characters?

How to write preg_match, to match string *My* ?
This doesn't work:
$ptn = "/\*(.*)\*/";
$str = "*My*";
preg_match($ptn, $str, $matches);
print_r($matches);
because it outputs:
Array
(
[0] => *My*
[1] => *My*
)
instead of:
Array
(
[0] => *My*
[1] => My
)
Works fine here:
php > preg_match('/\*(.*)\*/', '*My*', $matches);
php > var_dump($matches);
array(2) {
[0]=>
string(4) "*My*"
[1]=>
string(2) "My"
}
Remember that the $matches array will ALWAYS contain the entire matched string in position 0, then the individal matches in slots 1+.

PHP Regular Expression Does Not Work

I've been trying the next regular expression
$pattern = '/([0-9]{1,2}[.]{1}([a-z|A-Z|0-9]+[\s]*)+)/';
in order to detect the following occurences in a text : [number].[text],
for example : 1.text text text
For the next text"test number one 1.first 2.second" the result is
array(3) { [0]=> string(9) "1.first 2" [1]=> string(9) "1.first 2" [2]=> string(1) "2" }
Where is the problem in the regular expression I wrote?
Thanks in advance !
Is this what you are trying to do:
\d+[.][\w\d\s]+?(?=$|\s\d+[.])
It will match all the 3 occurrences in this text: "1. text test 2. some more22 3. and more"
Your problem is the plus at the end, which means you can match things after the space. It should be:
$pattern = '/([0-9]{1,2}[.]{1}([a-z|A-Z|0-9]+[\s]*))/';
Try this:
$pattern = '/\d\.\w+/';
$str = "test number one 1.first 2.second 3.third 4.xyz 5.abcd";
preg_match_all($pattern, $str, $m);
print_r( $m );
The output is:
Array
(
[0] => Array
(
[0] => 1.first
[1] => 2.second
[2] => 3.third
[3] => 4.xyz
[4] => 5.abcd
)
)
is that what you need ? I'm not sure that I get well what you need to match so please try to explain it a bit more
You can say for example:
I would like to match x numbers followed by . followed by n letters
or something like that

Regex to get repeating matches within a match

I have this sample string in a source:
#include_plugin:PluginName param1=value1 param2=value2#
What I want is to find all occurances of #include_plugin:*# from a source with a result of the PluginName and each paramN=valueN.
At this moment I'm fiddling with something like this (and have tried many variants): /#include_plugin:(.*\b){1}(.*\=.*){0,}#/ (using this resource). Unfortunately I can't seem to define a pattern which is giving me the result I want. Any suggestions?
Update with example:
Say I have this string in a .tpl-file. #include_plugin:BestSellers limit=5 fromCategory=123#
I want it to return an array with:
0 => BestSellers,
1 => limit=5 fromCategory=123
Or even better (if possible):
0 => BestSellers,
1 => limit=5,
2 => fromCategory=123
You can do it in 2 steps. First capture the line with a regex, then explode the parameters into an array:
$subject = '#include_plugin:PluginName param1=value1 param2=value2#';
$pattern = '/#include_plugin:([a-z]+)( .*)?#/i';
preg_match($pattern, $subject, $matches);
$pluginName = $matches[1];
$pluginParams = isset($matches[2])?explode(' ', trim($matches[2])):array();
You can use this regex:
/#include_plugin:([a-zA-Z0-9]+)(.*?)#/
The PluginName is in the first capturing group, and the parameters are in the second capturing group. Note that the parameters, if any, has a leading spaces.
It is not possible to write a regex to extract to your even better case, unless the maximum number of parameters in known.
You can do extra processing by first trimming leading and trailing spaces, then split along /\s+/.
I'm not sure of your character-set that your PluginName can contain, or the parameters/values, but in case they are limited you can use the following regex:
/#include_plugin:((?:\w+)(?:\s+[a-zA-Z0-9]+=[a-zA-Z0-9]+)*)#/
This will capture the plugin name followed by any list of alpha-numeric parameters with their values. The output can be seen with:
<?
$str = '#include_plugin:PluginName param1=value1 param2=value2#
#include_plugin:BestSellers limit=5 fromCategory=123#';
$regex = '/#include_plugin:((?:\w+)(?:\s+[a-zA-Z0-9]+=[a-zA-Z0-9]+)*)#/';
$matches = array();
preg_match_all($regex, $str, $matches);
print_r($matches);
?>
This will output:
Array
(
[0] => Array
(
[0] => #include_plugin:PluginName param1=value1 param2=value2#
[1] => #include_plugin:BestSellers limit=5 fromCategory=123#
)
[1] => Array
(
[0] => PluginName param1=value1 param2=value2
[1] => BestSellers limit=5 fromCategory=123
)
)
To get the array in the format you need, you can iterate through the results with:
$plugins = array();
foreach ($matches[1] as $match) {
$plugins[] = explode(' ', $match);
}
And now you'll have the following in $plugins:
Array
(
[0] => Array
(
[0] => PluginName
[1] => param1=value1
[2] => param2=value2
)
[1] => Array
(
[0] => BestSellers
[1] => limit=5
[2] => fromCategory=123
)
)
$string = "#include_plugin:PluginName1 param1=value1 param2=value2# #include_plugin:PluginName2#";
preg_match_all('/#include_plugin:([a-zA-Z0-9]+)\s?([^#]+)?/', $string, $matches);
var_dump($matches);
is this what you are looking for?
array(3) {
[0]=>
array(2) {
[0]=>
string(55) "#include_plugin:PluginName1 param1=value1 param2=value2"
[1]=>
string(27) "#include_plugin:PluginName2"
}
[1]=>
array(2) {
[0]=>
string(11) "PluginName1"
[1]=>
string(11) "PluginName2"
}
[2]=>
array(2) {
[0]=>
string(27) "param1=value1 param2=value2"
[1]=>
string(0) ""
}
}
This Regex will give you multiple groups, one for each plugin.
((?<=#include_plugin:)(.+))

PHP's preg_match() and preg_match_all() functions

What do the preg_match() and preg_match_all() functions do and how can I use them?
preg_match stops looking after the first match. preg_match_all, on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.
http://php.net/manual/en/function.preg-match-all.php
Both preg_match and preg_match_all functions in PHP use Perl compatible regular expressions.
You can watch this series to fully understand Perl compatible regular expressions: https://www.youtube.com/watch?v=GVZOJ1rEnUg&list=PLfdtiltiRHWGRPyPMGuLPWuiWgEI9Kp1w
preg_match($pattern, $subject, &$matches, $flags, $offset)
The preg_match function is used to search for a particular $pattern in a $subject string and when the pattern is found the first time, it stops searching for it. It outputs matches in the $matches, where $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized sub-pattern, and so on.
Example of preg_match()
<?php
preg_match(
"|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$matches
);
var_dump($matches);
Output:
array(2) {
[0]=>
string(16) "<b>example: </b>"
[1]=>
string(9) "example: "
}
preg_match_all($pattern, $subject, &$matches, $flags)
The preg_match_all function searches for all the matches in a string and outputs them in a multi-dimensional array ($matches) ordered according to $flags. When no $flags value is passed, it orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized sub-pattern, and so on.
Example of preg_match_all()
<?php
preg_match_all(
"|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$matches
);
var_dump($matches);
Output:
array(2) {
[0]=>
array(2) {
[0]=>
string(16) "<b>example: </b>"
[1]=>
string(36) "<div align=left>this is a test</div>"
}
[1]=>
array(2) {
[0]=>
string(9) "example: "
[1]=>
string(14) "this is a test"
}
}
A concrete example:
preg_match("/find[ ]*(me)/", "find me find me", $matches):
$matches = Array(
[0] => find me
[1] => me
)
preg_match_all("/find[ ]*(me)/", "find me find me", $matches):
$matches = Array(
[0] => Array
(
[0] => find me
[1] => find me
)
[1] => Array
(
[0] => me
[1] => me
)
)
preg_grep("/find[ ]*(me)/", ["find me find me", "find me findme"]):
$matches = Array
(
[0] => find me find me
[1] => find me findme
)

Categories