How to check specific string sequance using the regular expression in PHP - php

I am trying to create a regular expression to extract company details from a list of companies, but is facing difficulty because some companies have their mobile number listed before the company code and some have it listed after. They only want to match companies that have the mobile number listed after the company code and have tried using a look ahead in the regular expression but it hasn't been successful.
my regex syntax
details of the company:(?<address>[^\n\r]*)\b(?!.*mobile).*(company-code:)(.*?)(mobile:)(.*?)
strings to be checked:
details of the company: name:xyz, company-code:100, mobile:123
details of the company: name:xyz, mobile:12345, company-code:100

I suggest looking at it a little differently. From a more generic perspective your strings have a pattern of prefix: field1:value1, field2:value2, .... So you can focus on matching the field:value pairs. Using preg_match_all() you can fetch all matches as sets.
$data = [
'details of the company: name:xyz, company-code:100, mobile:123',
'details of the company: name:xyz, mobile:12345, company-code:100',
];
$pattern = '((?<field>[a-z-]+):\s*(?<value>[^,:]+)(?:,|$))';
$companies = [];
foreach ($data as $subject) {
if (preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER)) {
// new company array
$company = [];
// iterate and add found fields
foreach ($matches as $match) {
$company[$match['field']] = $match['value'];
}
// add company array to list
$companies[] = $company;
}
}
var_dump($companies);
Output:
array(2) {
[0]=>
array(3) {
["name"]=>
string(3) "xyz"
["company-code"]=>
string(3) "100"
["mobile"]=>
string(3) "123"
}
[1]=>
array(3) {
["name"]=>
string(3) "xyz"
["mobile"]=>
string(5) "12345"
["company-code"]=>
string(3) "100"
}
}
Another solution would be to use string functions. Remove all unnecessary parts from the subject and then split it.
$prefix = 'details of the company: ';
$companies = [];
foreach ($data as $subject) {
$subject = substr($subject, strlen($prefix));
$pairs = explode(',', $subject);
$company = [];
foreach ($pairs as $pair) {
[$field, $value] = explode(':', $pair);
$company[trim($field)] = trim($value);
}
$companies[] = $company;
}
var_dump($companies);

Related

php regex lookahead - exclude character

I’m trying to extract three parts with a regular expression.
It works for the controller and the id but not for the slug, I can not remove the last -
<?php
$url = "/cockpit/posts/my-second-article-2-155";
$routes = [];
$patterns = "/(?<controller>[a-z]+)\/(?<slug>[a-z0-9\-]+)(?<=\-)(?<id>[0-9]+)/i";
preg_match($patterns, $url, $matches);
foreach ($matches as $key => $value){
if(!is_numeric($key)){
$routes[$key] = $value;
}
}
var_dump($routes);
I get the following result :
array(3) {
["controller"]=>
string(5) "posts"
["slug"]=>
string(20) "my-second-article-2-"
["id"]=>
string(3) "155"
}
But i want this slug :
["slug"]=>
string(20) "my-second-article-2"
Thanks
You may use the following regex pattern:
/(?<controller>[a-z]+)\/(?<slug>[a-z0-9]+(?:-[a-z0-9]+)+)-(?<id>[0-9]+)/i
Your updated PHP script:
$url = "/cockpit/posts/my-second-article-2-155";
$routes = [];
$patterns = "/(?<controller>[a-z]+)\/(?<slug>[a-z0-9]+(?:-[a-z0-9]+)+)-(?<id>[0-9]+)/i";
preg_match($patterns, $url, $matches);
foreach ($matches as $key => $value) {
if (!is_numeric($key)) {
$routes[$key] = $value;
}
}
var_dump($routes);
This prints:
array(3) {
["controller"]=>
string(5) "posts"
["slug"]=>
string(19) "my-second-article-2"
["id"]=>
string(3) "155"
}
The final portion of the updated regex says to match:
[a-z0-9]+ alphanumeric term
(?:-[a-z0-9]+)+ followed by hyphen and another alphanumeric term, both 1 or more times
- match a literal hyphen
[0-9]+ match the id

php function for rading out values from string

i want to make a php loop that puts the values from a string in 2 different variables.
I am a beginner. the numbers are always the same like "3":"6" but the length and the amount of numbers (always even). it can also be "23":"673",4:6.
You can strip characters other than numbers and delimiters, and then do explode to get an array of values.
$string = '"23":"673",4:6';
$string = preg_replace('/[^\d\:\,]/', '', $string);
$pairs = explode(',', $string);
$pairs_array = [];
foreach ($pairs as $pair) {
$pairs_array[] = explode(':', $pair);
}
var_dump($pairs_array);
This gives you:
array(2) {
[0]=>
array(2) {
[0]=>
string(2) "23"
[1]=>
string(3) "673"
}
[1]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "6"
}
}
<?php
$string = '"23":"673",4:6';
//Remove quotes from string
$string = str_replace('"','',$string);
//Split sring via comma (,)
$splited_number_list = explode(',',$string);
//Loop first list
foreach($splited_number_list as $numbers){
//Split numbers via colon
$splited_numbers = explode(':',$numbers);
//Numbers in to variable
$number1 = $splited_numbers[0];
$number2 = $splited_numbers[1];
echo $number1." - ".$number2 . "<br>";
}
?>

Get between brackets and word PHP

Im trying to extract a specific value from multiple strings. Lets say i have the following strings:
/a-url/{some_hash}/
/user/{user_hash}/
/user-overview/{date_hash}/{user_hash}
I want to extract all between curly bracket open and _hash}, how can i achieve this?
The output should be a array:
$array = [
'some_hash',
'user_hash',
'date_hash',
'user_hash'
];
Current code:
$matches = [];
foreach (\Route::getRoutes()->getRoutes() as $route) {
$url = $route->getUri();
preg_match_all('/({.*?_hash})/', $url, $matches);
}
You can use regex for that:
$s = '/a-url/{some_hash}/
/user/{user_hash}/
/user-overview/{date_hash}/{user_hash}';
preg_match_all('/{(.*?_hash)}/', $s, $m);
var_dump($m[1]);
The output will be:
array(4) {
[0]=>
string(9) "some_hash"
[1]=>
string(9) "user_hash"
[2]=>
string(9) "date_hash"
[3]=>
string(9) "user_hash"
}
Based on your edit you probably want:
$all_matches = [];
foreach (\Route::getRoutes()->getRoutes() as $route) {
$url = $route->getUri();
preg_match_all('/{(.*?_hash)}/', $url, $matches);
$all_matches = array_merge($all_matches, $matches[1]);
}
var_dump($all_matches);

Building a multidimensional Array with another Array in PHP

I try to build an array. I don't wanna write something like $array[3][5][8] = []. Because the count of the first Array can change, here it's 3 but it also can be like 9 or 12. Also the values can change, but they are always unique numbers. I hope someone knows a better way. Thank you.
// First Array, which I have. The count and the content can change.
array(3) {
[0]=>
string(1) "3"
[1]=>
string(1) "5"
[2]=>
string(1) "8"
}
// Second Array, thats the goal.
array(1) {
[3]=>
array(1) {
[5]=>
array(1) {
[8]=>
array(0) {
}
}
}
}
This code will solve your problem:
$array = [3,5,8,9]; // your first array
$newArray = null;
foreach ($array as $value) {
if($newArray === null) {
$newArray[$value] = [];
$ref = &$newArray[$value];
}
else {
$ref[$value] = [];
$ref = &$ref[$value];
}
}
$newArray - holds the result you wanted
$array1=array(3,5,8);
$array2=array();
for($i=count($array1);$i>0;$i--){
$temp=array();
$temp[$array1[$i-1]]=$array2;
$array2=$temp;
}
$subject is the reference to the array you are currently in.
$array is the main root array that you obtain in the end.
$input is the input int array.
$subject = $array = [];
foreach($input as $key){
$subject[$key] = []; // create empty array
$subject =& $subject[$key]; // set reference to child
// Now $subject is the innermost array.
// Editing $subject will change the most nested value in $array
}

split a comma separated string in a pair of 2 using php

I have a string having 128 values in the form of :
1,4,5,6,0,0,1,0,0,5,6,...1,2,3.
I want to pair in the form of :
(1,4),(5,6),(7,8)
so that I can make a for loop for 64 data using PHP.
You can accomplish this in these steps:
Use explode() to turn the string into an array of numbers
Use array_chunk() to form groups of two
Use array_map() to turn each group into a string with brackets
Use join() to glue everything back together.
You can use this delicious one-liner, because everyone loves those:
echo join(',', array_map(function($chunk) {
return sprintf('(%d,%d)', $chunk[0], isset($chunk[1]) ? $chunk[1] : '0');
}, array_chunk(explode(',', $array), 2)));
Demo
If the last chunk is smaller than two items, it will use '0' as the second value.
<?php
$a = 'val1,val2,val3,val4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = array(array_shift($buffer), array_shift($buffer)); }
return $result;
}
$result = x($a);
var_dump($result);
?>
Shows:
array(2) { [0]=> array(2) { [0]=> string(4) "val1" [1]=> string(4) "val2" } [1]=> array(2) { [0]=> string(4) "val3" [1]=> string(4) "val4" } }
If modify it, then it might help you this way:
<?php
$a = '1,2,3,4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = sprintf('(%d,%d)', array_shift($buffer), array_shift($buffer)); }
return implode(',', $result);
}
$result = x($a);
var_dump($result);
?>
Which shows:
string(11) "(1,2),(3,4)"

Categories