Getting multiple number from a string - php

I have a form and one of the input names has numbers that correspond to information in my database. I need to extract the numbers and set them as variables so I can use them to store and retrieve data from the database.
Example: rdobtn_1_15 or qtybx_9_82
then numbers will be dynamic and will change so I need something that will get the numbers whether they are "20" or "5327"

$input = 'rdobtn_1_15'
$matches = null;
$returnValue = preg_match('/_(\\d+)_(\\d+)/', $input, $matches);
Your matches will be stored as
array (
0 => '_1_15',
1 => '1',
2 => '15',
)
So your numbers are accessable via
echo $matches[1] // 1
echo $matches[2] // 15
For reference: Regular Expressions

You can extract the digits from a string, if this is what you want to achieve, with:
preg_match_all('!\d+!', $your_string, $matches);
print_r($matches);

$array = explode('_', $string);
$element = $array[5]; // or whichever element you want

Related

Extract whole number between 2 slashes

I'm trying to extract id, which is a whole number from a url, for example:
http://example.com/email/verify/106/8be57f01ac84747886acd7ae88c888112135fc7a
I'd like to extract only 106 from the string in PHP. The only dynamic variables in the URL would be the domain and the hash after 106/ The domain, id, and hash after 106/ are all dynamic.
I've tried preg_match_all('!\d+!', $url, $result), but it matches all number in string.
Any tips?
The pattern \b\d+\b might be specific enough here:
$url = "http://example.com/email/verify/106/8be57f01ac84747886acd7ae88c888112135fc7a";
preg_match_all('/\b\d+\b/', $url, $matches);
print_r($matches[0]);
This prints:
Array
(
[0] => 106
)
Try this. This will works.
$url = $_SERVER['REQUEST_URI']; //"http://example.com/email/verify/106/8be57f01ac84747886acd7ae88c888112135fc7a";
$str = explode('/',$url);
echo "<pre>";
print_r($str);
$id = $str[5]; // 106

PHP Regex for a specific numeric value inside a comma-delimited integer number string

I am trying to get the integer on the left and right for an input from the $str variable using REGEX. But I keep getting the commas back along with the integer. I only want integers not the commas. I have also tried replacing the wildcard . with \d but still no resolution.
$str = "1,2,3,4,5,6";
function pagination()
{
global $str;
// Using number 4 as an input from the string
preg_match('/(.{2})(4)(.{2})/', $str, $matches);
echo $matches[0]."\n".$matches[1]."\n".$matches[1]."\n".$matches[1]."\n";
}
pagination();
How about using a CSV parser?
$str = "1,2,3,4,5,6";
$line = str_getcsv($str);
$target = 4;
foreach($line as $key => $value) {
if($value == $target) {
echo $line[($key-1)] . '<--low high-->' . $line[($key+1)];
}
}
Output:
3<--low high-->5
or a regex could be
$str = "1,2,3,4,5,6";
preg_match('/(\d+),4,(\d+)/', $str, $matches);
echo $matches[1]."<--low high->".$matches[2];
Output:
3<--low high->5
The only flaw with these approaches is if the number is the start or end of range. Would that ever be the case?
I believe you're looking for Regex Non Capture Group
Here's what I did:
$regStr = "1,2,3,4,5,6";
$regex = "/(\d)(?:,)(4)(?:,)(\d)/";
preg_match($regex, $regStr, $results);
print_r($results);
Gives me the results:
Array ( [0] => 3,4,5 [1] => 3 [2] => 4 [3] => 5 )
Hope this helps!
Given your function name I am going to assume you need this for pagination.
The following solution might be easier:
$str = "1,2,3,4,5,6,7,8,9,10";
$str_parts = explode(',', $str);
// reset and end return the first and last element of an array respectively
$start = reset($str_parts);
$end = end($str_parts);
This prevents your regex from having to deal with your numbers getting into the double digits.

Error parsing regex pattern in php

I want to split a string such as the following (by a divider like '~##' (and only that)):
to=enquiry#test.com~##subject=test~##text=this is body/text~##date=date
into an array containing e.g.:
to => enquiry#test.com
subject => test
text => this is body/text
date => date
I'm using php5 and I've got the following regex, which almost works, but there are a couple of errors and there must be a way to do it in one go:
//Split the string in the url of $text at every ~##
$regexp = "/(?:|(?<=~##))(.*?=.*?)(?:~##|$|\/(?!.*~##))/";
preg_match_all($regexp, $text, $a);
//$a[1] is an array containing var1=content1 var2=content2 etc;
//Now create an array in the form [var1] = content, [var2] = content2
foreach($a[1] as $key => $value) {
//Get the two groups either side of the equals sign
$regexp = "/([^\/~##,= ]+)=([^~##,= ]+)/";
preg_match_all($regexp, $value, $r);
//Assign to array key = value
$val[$r[1][0]] = $r[2][0]; //e.g. $val['subject'] = 'hi'
}
print_r($val);
My queries are that:
It doesn't seem to capture more than 3 different sets of parameters
It is breaking on the # symbol and so not capturing email addresses e.g. returning:
to => enquiry
subject => test
text => this is body/text
I am doing multiple different regex searches where I suspect I would be able to do one.
Any help would be really appreciated.
Thanks
Why are you using regex when there is much simple method to do this by explode like this
$str = 'to=enquiry#test.com~##subject=test~##text=this is body/text~##date=date';
$array = explode('~##',$str);
$finalArr = array();
foreach($array as $val)
{
$tmp = explode('=',$val);
$finalArr[$tmp['0']] = $tmp['1'];
}
echo '<pre>';
print_r($finalArr);

Split variable using php

I am grabbing the name attribute using jquery and passing it to my Controller via ajax call.
VIEW
<?php
$data = array(
'name' => $id.$country,
'class' => 'send',
'content' => 'Send'
);
echo form_button($data);
?>
JS
var abc = $(self).attr("name");
I would like to know if there is any codeigniter php function which can help me to separate id from country and pass them to my model.
CONTROLLER
$abc = $this->input->post('abc');
$id = first part of abc variable
$country = second part of abc variable
DISCLAIMER:
As #Jonast92 clarified in the comments this answer doesn't solve the solution, and i agree after re-looking at the question since the values do not actually contain a dot and are not in the form of 1.usa but rather 1usa.
Note: I'll leave the initial answer below for reference but this would only work if the characters were separated by a (.) character and not concatenated directly.
Semi-Invalid Answer:
IF the string was concatenated using a . as a separator as in:
'name' => $id . "." . $country,
You could explode that concatenated string into an array using:
$abc = explode(".",$abc);
Then the id will be stored at index 0 and country at index 1:
$id = $abc[0];
$country = $abc[1];
Just make sure that values do not contain any dot (.) characters as that would produce unwanted results.
Note: You can even limit the number of array elements using:
$abc = explode(".",$abc,2);
which will allow countries to still contain a dot without them breaking up further into an array.
Optimal Solution though would be to split those two values and pass them as seperate parameters before even posting them to the php page and only concatenate them if necessary for your application elsewhere.
Can you try this:
$str = $this->input->post('abc');
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
EXAMPLE:
$str = '1654usa';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
To echo out the number use: echo $matches[0][0];
This will return 1654, because the regular expression searches the string for numbers, and will "pull out" all the numbers.
This should work for you if the id only contains numbers!
<?php
$str = '234534534Virgin Islands (U.S.)';
preg_match_all('!\d+!', $str, $matches);
$id = $matches[0][0];
preg_match_all('/((?!\d+).)*$/', $str, $matches);
$country = $matches[0][0];
echo $id . "<br />" . $country;
?>
Output:
234534534
Virgin Islands (U.S.)

A bit lost with preg_match regular expression

I'm a beginner in regular expression so it didn't take long for me to get totally lost :]
What I need to do:
I've got a string of values 'a:b,a2:b2,a3:b3,a4:b4' where I need to search for a specific pair of values (ie: a2:b2) by the second value of the pair given (b2) and get the first value of the pair as an output (a2).
All characters are allowed (except ',' which seperates each pair of values) and any of the second values (b,b2,b3,b4) is unique (cant be present more than once in the string)
Let me show a better example as the previous may not be clear:
This is a string: 2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,never:0
Searched pattern is: 5
I thought, the best way was to use function called preg_match with subpattern feature.
So I tried the following:
$str = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
$re = '/(?P<name>\w+):5$/';
preg_match($re, $str, $matches);
echo $matches['name'];
Wanted output was '5 minutes' but it didn't work.
I would also like to stick with Perl-Compatible reg. expressions as the code above is included in a PHP script.
Can anyone help me out? I'm getting a little bit desperate now, as Ive spent on this most of the day by now ...
Thanks to all of you guys.
$str = '2 minutes:2,51 seconds:51,5 minutes:5,10 minutes:10,15 minutes:51,never:0';
$search = 5;
preg_match("~([^,\:]+?)\:".preg_quote($search)."(?:,|$)~", $str, $m);
echo '<pre>'; print_r($m); echo '</pre>';
Output:
Array
(
[0] => 5 minutes:5
[1] => 5 minutes
)
$re = '/(?:^|,)(?P<name>[^:]*):5(?:,|$)/';
Besides the problem of your expression having to match $ after 5, which would only work if 5 were the last element, you also want to make sure that after 5 either nothing comes or another pair comes; that before the first element of the pair comes either another element or the beginning of the string, and you want to match more than \w in the first element of the pair.
A preg_match call will be shorter for certain, but I think I wouldn't bother with regular expressions, and instead just use string and array manipulations.
$pairstring = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
function match_pair($searchval, $pairstring) {
$pairs = explode(",", $str);
foreach ($pairs as $pair) {
$each = explode(":", $pair);
if ($each[1] == $searchval) {
echo $each[0];
}
}
}
// Call as:
match_pair(5, $pairstring);
Almost the same as #Michael's. It doesn't search for an element but constructs an array of the string. You say that values are unique so they are used as keys in my array:
$str = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
$a = array();
foreach(explode(',', $str) as $elem){
list($key, $val) = explode(':', $elem);
$a[$val] = $key;
}
Then accessing an element is very simple:
echo $a[5];

Categories