I'm using a regex to check a string for a certain format.
preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE);
Using this regex, the posted string needs to have this format:
/answer n x
n -> an integer > 0
x -> a string, 512 chars maximum
Now how to extract "n" and "x" the easiest way using PHP?
For example:
/answer 56 this is my sample text
Should lead to:
$value1 = 56;
$value2 = "this is my sample text";
Running this simple piece of code
<?php
$hit = [];
$str = '/answer 56 this is my sample text';
preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE);
echo'<pre>',print_r($hit),'</pre>';
Will show you, that $hit has following values:
<pre>Array
(
[0] => Array
(
[0] => /answer 56 this is my sample text
[1] => 0
)
[1] => Array
(
[0] => 56
[1] => 8
)
[2] => Array
(
[0] => this is my sample text
[1] => 11
)
)
1</pre>
Here:
$hit[0][0] is full string that matches your pattern
$hit[1][0] is a substring that matches pattern [1-9][0-9]*
$hit[2][0] is a substring that matches pattern .{1,512}
So,
$value1 = $hit[1][0];
$value2 = $hit[2][0];
Related
I have a string and I need to find all occurrences of some substrings in it but I know only initials chars of substrings... Ho can I do?
Example:
$my_string = "This is a text cointaining [substring_aaa attr], [substring_bbb attr] and [substring], [substring], [substring] and I'll try to find them!";
I know all substrings begin with '[substring' and end with a space char (before attr) or ']' char, so in this example I need to find substring_aaa, substring_bbb and substring and count how many occurrences for each one of them.
The result would be an associative array with the substrings as keys and occurrerrences as values, example:
$result = array(
'substring' => 3,
'substring_aaa' => 1,
'substring_bbb' => 1
)
Match [substring and then NOT ] zero or more times and then a ]:
preg_match_all('/\[(substring[^\]]*)\]/', $my_string, $matches);
$matches[1] will yield:
Array
(
[0] => substring_aaa attr
[1] => substring_bbb attr
[2] => substring
[3] => substring
[4] => substring
)
Then you can count the values:
$result = array_count_values($matches[1]);
After rereading the question, if you don't want what comes after a space (attr in this case) then:
preg_match_all('/\[(substring[^\]\s]*)[\]\s]/', $my_string, $matches);
For which $matches[1] will yield:
Array
(
[0] => substring_aaa
[1] => substring_bbb
[2] => substring
[3] => substring
[4] => substring
)
With the array_count_values yielding:
Array
(
[substring_aaa] => 1
[substring_bbb] => 1
[substring] => 3
)
My situation is: I'm processing an array word by word. What I'm hoping to do and
working on, is to capture a certain word. But for that I need to test two patterns or more with preg-match.
This is my code :
function search_array($array)
{
$pattern = '[A-Z]{1,3}[0-9]{1,3}[A-Z]{1,2}[0-9]{1,2}[A-Z]?';
$pattern2 = '[A-Z]{1,7}[0-9]{1,2}';
$patterns = array($pattern, $pattern2);
$regex = '/(' .implode('|', $patterns) .')/i';
foreach ($array as $str) {
if (preg_match ($regex, $str, $m)){
$matches[] = $m[1];
return $matches[0];
}
}
}
Example of array I could have :
Array ( [0] => X [1] => XXXXXXX [2] => XXX [3] => XXXX [4] => ABC01DC4 )
Array ( [0] => X [1] => XXXXXXX [2] => XXX [3] => ABCDEF4 [4] => XXXX [5] => XX )
Words I would like to catch :
-In the first array : ABC01DC4
-In the second array : ABCDEF4
The problem is not the pattern itself, it's the syntax to use multiple pattern in the same pregmatch
Your code worked with me, and I didn't find any problem with the code or the REGEX. Furthermore, the description you provided is not enough to understand your needs.
However, I have guessed one problem after observing your code, which is, you didn't use any anchor(^...$) to perform matching the whole string. Your regex can find match for these inputs: %ABC01DC4V or ABCDEF4EE. So change this line with your code:
$regex = '/^(' .implode('|', $patterns) .')$/i';
-+- -+-
Under Return Values for Count()
Returns the number of elements in var. If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.
I have a string which is filled with letters and numbers and I'm using preg_match_all() to extract those numbers. As I recall preg_match_all fills the contents of the array given in the 3rd parameter with the results. Why does it return 1?
What am I doing wrong in my code?
$string = "9hsfgh563452";
preg_match_all("/[0-9]/",$string,$matches);
echo "Array size: " . count($matches)."</br>"; //Returns 1
echo "Array size: " . sizeof($matches)."</br>"; //Returns 1
print_r($matches);
I would like to sum the contents of the array (which is all the numbers returned in the string) array_sum() didn't work ; it is a string array and I don't know how to convert it to an int array because I'm not using any delimiters like ' , ' and such. Is there a more efficient way in doing this?
Help appreciated.
The count is 1 because $matches is an array which contains another array inside. Specifically, $matches[0] is an array that contains each match of the zero-th capturing group (the whole regular expression).
That is, $matches looks like this:
Array
(
[0] => Array // The key "0" means that matches for the whole regex follow
(
[0] => 9 // and here are all the single-character matches
[1] => 5
[2] => 6
[3] => 3
[4] => 4
[5] => 5
[6] => 2
)
)
The result of preg_match_all is actually an array of an array:
Array
(
[0] => Array
(
[0] => 9
[1] => 5
[2] => 6
[3] => 3
[4] => 4
[5] => 5
[6] => 2
)
)
So you'll need to do something like:
echo "Array size: " . count($matches[0]);
echo "Array sum: " . array_sum($matches[0]);
This is due to the way preg_match_all returns results. Its main array elements are the preg brackets (expression matches), whilst the contents of them are what you matched.
In your case, you have no sub-expressions. The array will therefore only have one element - and that element will contain all your digits.
To sum them up, simply do this:
$sum = 0;
$j = count($matches[0]);
for ($i = 0; i < $j; ++$i) {
$sum += (int)$matches[0][$i];
}
Try using $matches[0] instead of $matches (returns 7).
Then if you want to sum all the numbers you can use the foreach function
Here is an example string:
"60 reviews from 12 people, 20% of users"
(Let's call it $v)
I have been using preg_match_all to get an array with all the numbers
$pattern = '!\d+!';
preg_match_all($pattern, $v, $matches, PREG_SET_ORDER);
The result I get is:
Array
(
[0] => Array
(
[0] => 60
)
[1] => Array
(
[0] => 12
)
[2] => Array
(
[0] => 20
)
)
But despite trying for some time I haven't been able to get what I want. What I want is this:
Array
(
[0] => 60
[1] => 12
[2] => 20
)
Maybe should I be using preg_match instead? but with preg_match I only get one value... Or maybe along with a loop? It looks like an ugly hack... There should be a profesional way out there... Thanks in advance to PHP experts! ;)
Presuming the format always stays the same, you can do the following:
<?php
// Input string/line
$v = "60 reviews from 12 people, 20% of users";
// Match regex (0-9; min 1 or max unlimited numbers)
preg_match_all("/[0-9]{1,}/", $v, $matches);
// Remove/sub key
$matches = $matches[0];
// Echo out
print_r($matches);
?>
This will output:
Array (
[0] => 60 // < Access using $matches[0]
[1] => 12 // < Access using $matches[1]
[2] => 20 // < Access using $matches[2]
)
Is this what you want?, array_values($array)
Hi I need a preg_split regex that will split a string at substrings in square brackets.
This example input:
$string = 'I have a string containing [substrings] in [brackets].';
should provide this array output:
[0]= 'I have a string containing '
[1]= '[substrings]'
[2]= ' in '
[3]= '[brackets]'
[4]= '.'
After reading your revised question:
This might be what you want:
$string = 'I have a string containing [substrings] in [brackets].';
preg_split('/(\[.*?\])/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
You should get:
Array
(
[0] => I have a string containing
[1] => [substrings]
[2] => in
[3] => [brackets]
[4] => .
)
Original answer:
preg_split('/%+/i', 'ot limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');
You should get:
Array
(
[0] => ot limited to 3
[1] => so it can be
[2] => or
[3] => or
[4] => , etc Tha
)
Or if you want a mimimum of 3 then try:
preg_split('/%%%+/i', 'Not limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');
Have a go at http://regex.larsolavtorvik.com/
I think this is what you are looking for:
$array = preg_split('/(\[.*?\])/', $string, null, PREG_SPLIT_DELIM_CAPTURE);