Getting a variable from a certain pattern - php

I need to save the number between every pair of curly brackets as a variable.
{2343} -> $number
echo $number;
Output = 2343
I don't know how to do the '->' part.
I've found a similar function, but it simply removes the curly brackets and does nothing else.
preg_replace('#{([0-9]+)}#','$1', $string);
Is there any function I can use?

You'll probably want to use preg_match with a capture:
$subject = "{2343}";
$pattern = '/\{(\d+)\}/';
preg_match($pattern, $subject, $matches);
print_r($matches);
Output:
Array
(
[0] => {2343}
[1] => 2343
)
The $matches array will contain the result at index 1 if it is found, so:
if(!empty($matches) && isset($matches[1)){
$number = $matches[1];
}
If your input string can contain many numbers, then use preg_match_all:
$subject = "{123} {456}";
$pattern = '/\{(\d+)\}/';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => {123}
[1] => {456}
)
[1] => Array
(
[0] => 123
[1] => 456
)
)

$string = '{1234}';
preg_replace('#{([0-9]+)}#e','$number = $1;', $string);
echo $number;

Related

Regexp lookahead and lookbehind and match between certain characters

Currently I have this regexp to detect strings between double curly brackets and it work's wonderfully.
$str = "{{test}} and {{test2}}";
preg_match_all('/(?<={{)[^}]*(?=}})/', $str, $matches);
print_r($matches);
Returns:
Array
(
[0] => Array
(
[0] => test
[1] => test2
)
)
Now I need to expand it to only match stuff between ]] and [[
$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";
I've been trying to modify the regex but the lookahead and lookbehind is making it too difficult for me. How can I get it to match stuff inside ]] and [[ only?
Also I would like to match the whole string between ]] and [[ and then I would like to match each individual string between {{ }} inside it.
For example:
$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";
Would return:
Array
(
[0] => Array
(
[0] => {{test}} and {{test2}}
[1] => test
[2] => test2
)
)
Piggyback using preg_replace_callback:
$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";
$arr = array();
preg_replace_callback('/\]\](.*?)\[\[/', function($m) use (&$arr) {
preg_match_all('/(?<={{)[^}]*(?=}})/', $m[1], $arr); return true; }, $str);
print_r($arr[0]);
Output:
Array
(
[0] => test
[1] => test2
)

Need help understaing how preg_match works in php

I am new to using preg_match and I am having a hard time trying to grasp it. For example for this code below.. It only returns one match which is "h" .. isn't is supposed to return an array of 3 key value pairs?
$subject = "hey";
preg_match("/[a-z]/", $subject, $matches);
print_r($matches);
To return more matches you use preg_match_all() instead,
$subject = "hey";
preg_match_all("/[a-z]/", $subject, $matches);
print_r($matches);
This would print,
Array
(
[0] => Array
(
[0] => h
[1] => e
[2] => y
)
)

Finding the no of occurence of a string inside another string using regex in PHP?

I want to find the no of occurences of a sustring(pattern based) inside another string.
For example:
$mystring = "|graboard='KERALA'||graboarded='KUSAT'||graboard='MG'";
I want to find the no of graboards present in the $mystring,
So I used the regex for this, But how will I find the no of occurrence?
If you must use a regex, preg_match_all() returns the number of matches.
Use preg_match_all:
$mystring = "|graboard='KERALA'||graboarded='KUSAT'||graboard='MG'";
preg_match_all("/(graboard)='(.+?)'/i", $mystring, $matches);
print_r($matches);
will yield:
Array
(
[0] => Array
(
[0] => graboard='KERALA'
[1] => graboard='MG'
)
[1] => Array
(
[0] => graboard
[1] => graboard
)
[2] => Array
(
[0] => KERALA
[1] => MG
)
)
So then you can use count($matches[1]) -- however, this regex may need to be modified to suit your needs, but this is just a basic example.
Just use preg_match_all():
// The string.
$mystring="|graboard='KERALA'||graboarded='KUSAT'||graboard='MG'";
// The `preg_match_all()`.
preg_match_all('/graboard/is', $mystring, $matches);
// Echo the count of `$matches` generated by `preg_match_all()`.
echo count($matches[0]);
// Dumping the content of `$matches` for verification.
echo '<pre>';
print_r($matches);
echo '</pre>';

Regex to find sequential integers

I am having a difficult time getting my regular expression code to work properly in PHP. Here is my code:
$array = array(); // Used to satisfy the 3rd argument requirment of preg_match_all.
$regex = '/(012|345|678|987|654|321|123|456|789|876|543|210|234|567|765|432)/';
$subject = '123456';
echo preg_match_all($regex, $subject, $array).'<br />';
print_r($array);
When this code is ran it will output:
2
Array
(
[0] => Array
(
[0] => 123
[1] => 456
)
[1] => Array
(
[0] => 123
[1] => 456
)
)
What can I do so that it will match 123, 234, 345 and 456?
Thanks in advance!
Regex is not the right tool for this job (it's not going to return "sub-matches"). Simply use strpos in a loop.
$subject = '123456';
$seqs = array('012', '345', '678', '987', '654', '321', '123', '456', '234');
foreach ($seqs as $seq) {
if (strpos($subject, $seq) !== false) {
// found
}
}
$regex = '/(?=(012|345|678|987|654|321|123|456|789|876|543|210|234|567|765|432))/';
$subject = '123456';
preg_match_all($regex, $subject, $array);
print_r($array[1]);
output:
Array
(
[0] => 123
[1] => 234
[2] => 345
[3] => 456
)
You're trying to retrieve matches that overlap each other in the subject string, which in general is not possible. However, in many cases you can fake it by wrapping the whole regex in a capturing group, then wrapping that in a lookahead. Because the lookahead doesn't consume any characters when it matches, the regex engine manually bumps forward one position after each successful match, to avoid getting stuck in an infinite loop. But capturing groups still work, so you can retrieve the captured text in the usual way.
Notice that I only printed the contents of the first capturing group ($array[1]). If I had printed the whole array of arrays ($array), it would have looked like this:
Array
(
[0] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
[1] => Array
(
[0] => 123
[1] => 234
[2] => 345
[3] => 456
)
)
see it in action on ideone
It can be done with regular expressions. The problem with your original code is that as soon as a match occurs, the character is consumed and the regular expression will not backtrack. Here's one way to do it:
$array = array(); // Used to satisfy the 3rd argument requirment of preg_match_all.
$regex = '/012|345|678|987|654|321|123|456|789|876|543|210|234|567|765|432/';
$subject = '123456';
$tempSubject = $subject;
$finalAnswer = array();
do {
$matched = preg_match($regex, $tempSubject, $array);
$finalAnswer = array_merge($finalAnswer, $array);
$tempSubject = substr($tempSubject, 1);
} while ($matched && (strlen($tempSubject >= 3)));
print_r($finalAnswer);
As suggested in another answer, however, regular expressions might not be the correct tool to use in this situation, depending on your larger goal. In addition, the above code may not be the most efficient way (wrt memory or wrt performance) to solve this with regular expressions. It's just a striaghtforward fulfill-the-requirement solution.
Yeah it's a hack but you can use RegEx
<?php
$subject = '123456';
$rs = findmatches($subject);
echo '<pre>'.print_r($rs,true).'</pre><br />';
function findmatches($x) {
$regex = '/(\d{3})/';
// Loop through the subject string
for($counter = 0; $counter <= strlen($x); $counter++) {
$y = substr($x, $counter);
if(preg_match_all($regex, $y, $array)) {
$rs_array[$counter] = array_unique($array);
}
}
// Parse results array
foreach($rs_array as $tmp_arr) {
$rs[] = $tmp_arr[0][0];
}
return $rs;
}
?>
Returns:
Array
(
[0] => 123
[1] => 234
[2] => 345
[3] => 456
)
NOTE: This would only work with concurrent numbers

Splitting a string in certain way

I have the following string
{item1}home::::Home{/item1}{item2}contact_us::::Contact Us{/item2}{item3}.....
and so it goes on.
I need to split the string the following way
1=>{item1}home::::Home{/item1}
2=>{item2}contact_us::::Contact Us{/item2}
Is there a way?
$input = '{item1}home::::Home{/item1}{item2}contact_us::::Contact Us{/item2}{item3}.....';
$regex = '/{(\w+)}.*{\/\1}/';
preg_match_all($regex, $input, $matches);
print_r($matches[0]);
You could do it like this:
$text = "{item1}home::::Home{/item1}{item2}contact_us::::Contact Us{/item2}{item3}.....){/item3}";
preg_match_all('/{item\d}.+?{\/item\d}/', $text, $results);
var_dump($results) would produce:
Array
(
[0] => Array
(
[0] => {item1}home::::Home{/item1}
[1] => {item2}contact_us::::Contact Us{/item2}
[2] => {item3}.....){/item3}
)
)
Use preg_split() with the regex pattern /{.*?}.*?{\/.*?}/

Categories