How to extract certain words from a php string? - php

I have a long string like this I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];. Now I just want to get certain words like 'I1','I2','I8','NA1' and so on i.e. words between ':'&';' only ,and store them in array. How to do that efficiently?
I have already tried using preg_split() and it works but giving me wrong output. As shown below.
// $a is the string I want to extract words from
$str = preg_split("/[;:]/", $a);
print_r($str);
The output I am getting is this
Array
(
[0] => I8
[1] => 2
[2] => I1
[3] => 1
[4] => I2
[5] => 2
[6] => I3
[7] => 2
[8] => I4
[9] => 4
[10] =>
)
Array
(
[0] => NA1
[1] => 5
[2] =>
)
Array
(
[0] => IA1
[1] => [1,2,3,4,5]
[2] =>
)
Array
(
[0] => S1
[1] => asadada
[2] =>
)
Array
(
[0] => SA1
[1] => [1,2,3,4,5]
[2] =>
)
But I am expecting 'I8','I1','I2','I3','I4' also in seperated array with position [0]. Any help on how to do this.

You could try something like.
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/(?:^|[;:])(\w+)/', $str, $result);
print_r($result[1]); // Matches are here in $result[1]

You can perform a greedy match to match the items between ; and : using preg_match_all()
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/;(.+?)\:/',$str,$matches);
print_r($matches[1]);
Live Demo: https://3v4l.org/eBsod

One possible approach is using a combination of explode() and implode(). The result is returned as a string, but you can easily put it into an array for example.
<?php
$input = "I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];.";
$output = array();
$array = explode(";", $input);
foreach($array as $item) {
$output[] = explode(":", $item)[0];
}
echo implode(",", $output);
?>
Output:
I1,I2,I8,NA1,IA1,S1,SA1,SA1,.

Related

PHP - Preg Match All - Wordpress Multiple short codes with multiple parameters

I'm trying to find a regex capable of capturing the content of short codes produces in Wordpress.
My short codes have the following structure:
[shortcode name param1="value1" param2="value2" param3="value3"]
The number of parameters is variable.
I need to capture the shortcode name, the parameter name and its value.
The closest results I have achieved is with this:
/(?:\[(.*?)|\G(?!^))(?=[^][]*])\h+([^\s=]+)="([^\s"]+)"/
If I have the following content in the same string:
[specs product="test" category="body"]
[pricelist keyword="216"]
[specs product="test2" category="network"]
I get this:
0=>array(
0=>[specs product="test"
1=> category="body"
2=>[pricelist keyword="216"
3=>[specs product="test2"
4=> category="network")
1=>array(
0=>specs
1=>
2=>pricelist
3=>specs
4=>)
2=>array(
0=>product
1=>category
2=>keyword
3=>product
4=>category)
3=>array(
0=>test
1=>body
2=>216
3=>test2
4=>network)
)
I have tried different regex models but I always end up with the same issue, if I have more than one parameter, it fails to detect it.
Do you have any idea of how I could achieve this?
Thanks
Laurent
You could make use of the \G anchor using 3 capture groups, where capture group 1 is the name of the shortcode, and group 2 and 3 the key value pairs.
Then you can remove the first entry of the array, and remove the empty entries in the 1st, 2nd and 3rd entry.
This is a slightly updated pattern
(?:\[(?=[^][]*])(\w+)|\G(?!^))\h+(\w+)="([^"]+)"
Regex demo | Php demo
Example
$s = '[specs product="test" category="body"]';
$pattern = '/(?:\[(?=[^][]*])(\w+)|\G(?!^))\h+(\w+)="([^"]+)"/';
$strings = [
'[specs product="test" category="body"]',
'[pricelist keyword="216"]',
'[specs product="test2" category="network" key="value"]'
];
foreach($strings as $s) {
if (preg_match_all($pattern, $s, $matches)) {
unset($matches[0]);
$matches = array_map('array_filter', $matches);
print_r($matches);
}
}
Output
Array
(
[1] => Array
(
[0] => specs
)
[2] => Array
(
[0] => product
[1] => category
)
[3] => Array
(
[0] => test
[1] => body
)
)
Array
(
[1] => Array
(
[0] => pricelist
)
[2] => Array
(
[0] => keyword
)
[3] => Array
(
[0] => 216
)
)
Array
(
[1] => Array
(
[0] => specs
)
[2] => Array
(
[0] => product
[1] => category
[2] => key
)
[3] => Array
(
[0] => test2
[1] => network
[2] => value
)
)

Converting a string into an array of fixed length

I have a string that I want to convert into an array of 6 elements.
$x=Address : "MK/LK G8, 2ND FLR, MALAL VISO INFO 19-Aug-15 Acct Number : _254566003 etc...
IF I want an array
$parts[0]=MK/LKG......Length should be 6 (whitespace wont consider)
$parts[1]=82NDFLRLength should be 6
$parts[2]=etc.....
try this to split strings to array
$str = "MK/LK G8, 2ND FLR, MALAL VISO INFO 19-Aug-15 Acct Number : _254566003 etc..."
$arr = str_split($str, 6);
Simply use str_split along with the preg_replace as
$x="MK/LK G8, 2ND FLR, MALAL VISO INFO 19-Aug-15 Acct Number : _254566003 etc..";
$res = str_split(preg_replace('/\s/','',$x),6);
print_r($res);
Output:
Array
(
[0] => MK/LKG
[1] => 8,2NDF
[2] => LR,MAL
[3] => ALVISO
[4] => INFO19
[5] => -Aug-1
[6] => 5AcctN
[7] => umber:
[8] => _25456
[9] => 6003et
[10] => c..
)
Demo

To explode the string based on the special characters in Php

I have a string:
xyz.com?username="test"&pwd="test"#score="score"#key="1234"
output format:
array (
[0] => username="test"
[1] => pwd="test"
[2] => score="score"
[3] => key="1234"
)
This should work for you:
Just use preg_split() with a character class with all delimiters in it. At the end just use array_shift() to remove the first element.
<?php
$str = 'xyz.com?username="test"&pwd="test"#score="score"#key="1234"';
$arr = preg_split("/[?&##]/", $str);
array_shift($arr);
print_r($arr);
?>
output:
Array
(
[0] => username="test"
[1] => pwd="test"
[2] => score="score"
[3] => key="1234"
)
You can use preg_split function with regex pattern including all those delimimting special characters. Then remove the first value of the array and reset keys:
$s = 'xyz.com?username="test"&pwd="test"#score="score"#key="1234"';
$a = preg_split('/[?&##]/',$s);
unset($a[0]);
$a = array_values($a);
print_r($a);
Output:
Array (
[0] => username="test"
[1] => pwd="test"
[2] => score="score"
[3] => key="1234"
)

PHP RegEx split to 2D array?

Is it possible to convert the following string in to an array with PHP and preg_match_all, e.g;
The string will always be one character and a number followed by a space.
String: "C1 X2 B10"
$array[0][type]=>"C"
$array[0][number]=>1
$array[1][type]=>"X"
$array[1][number]=>2
$array[2][type]=>"B"
$array[2][number]=>10
You can use named groups in your regex:
$str = "C1 X2 B10";
$re = '~(?P<type>[A-Z])(?P<number>\d+)~';
preg_match_all($re, $str, $m, PREG_SET_ORDER);
print_r($m);
which gives you
Array
(
[0] => Array
(
[0] => C1
[type] => C
[1] => C
[number] => 1
[2] => 1
)
[1] => Array
(
[0] => X2
[type] => X
[1] => X
[number] => 2
[2] => 2
)
etc
so you can use $m[1]['type'] directly.
Of course, you can always use the regex for this which is WAAAAY faster, but I wanted to show you that you can do it without regex. There are more ways to solve a problem. As Harvey Specter, the character from "Suits" would say: "If someone points a gun to your head, there are 146 ways you can defend yourself" ;)
Here... try this:
$string = 'C1 X2 B10';
$explode = explode(' ', $string);
$i = 0;
foreach ($explode as $exp){
$number = substr($exp, 1);
$letter = substr($exp, 0, 1);
$array[$i]['type'] = $letter;
$array[$i]['number'] = $number;
$i++;
}
echo '<pre>';
print_r($array);
echo '</pre>';
the output will be:
Array
(
[0] => Array
(
[type] => C
[number] => 1
)
[1] => Array
(
[type] => X
[number] => 2
)
[2] => Array
(
[type] => B
[number] => 10
)
)
WARNING!! This solution will work only if you have only 1 letter, only at the beginning, with space separated elements in the string!
Hope this helps! :D

Explode array three times

I have a string and I would like to explode with three differents patterns. The string looks like to :
country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4
I would like to get the differents parts of this two strings. The two lines are separated by a /n, the dates are separated by : and the link associated to date are separated with a ->
At the beginning I explode by the line break
$var = explode("\n", $var);
but when I tried to explode again this string, I get an error : *preg_split() expects parameter 2 to be string, array given*
How can I get the different parts ?
Thanks in advance.
Ideone link
Instead of using preg_split, consider using preg_match. You can write it as one big regex.
<?php
// Implicit newline. Adding \n would make an empty spot in the array
$str = "country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4";
$arr = split("\n", $str);
for ($i = 0; $i < count($arr); $i++) {
preg_match("/^(\w+)\:(\d\d\/\d\d\/\d\d)->(\w+)\:(\d\d\/\d\d\/\d\d)->(\w+)/", $arr[$i], $matches);
print_r($matches);
}
?>
Output:
Array
(
[0] => country:00/00/00->link:00/00/00->link2
[1] => country
[2] => 00/00/00
[3] => link
[4] => 00/00/00
[5] => link2
)
Array
(
[0] => country2:00/00/00->link3:00/00/00->link4
[1] => country2
[2] => 00/00/00
[3] => link3
[4] => 00/00/00
[5] => link4
)
EDIT
In your comment, you're posting dates with 4 digits, whereas in your question, they only had 2 digits.
Therefore you need to change the regex to:
/^(\w+)\:(\d\d\/\d\d\/\d\d\d\d)->(\w+)\:(\d\d\/\d\d\/\d\d\d\d)->(\w+)/
How about using preg_match_all:
<?php
$data =<<<ENDDATA
country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4
ENDDATA;
preg_match_all('#(\d{2}/\d{2}/\d{2})->(.[^:\n]+)#', $data, $matches);
print_r($matches);
Gives the following result:
Array
(
[0] => Array
(
[0] => 00/00/00->link
[1] => 00/00/00->link2
[2] => 00/00/00->link3
[3] => 00/00/00->link4
)
[1] => Array
(
[0] => 00/00/00
[1] => 00/00/00
[2] => 00/00/00
[3] => 00/00/00
)
[2] => Array
(
[0] => link
[1] => link2
[2] => link3
[3] => link4
)
)
your problem is that after using explode first time, it is turning into an array and explode function connat explode an array. You need to use a loop probablr for loop that targets array elemets then use explode function on those elements and you will have it.
See example Below:
<?php
$val="abc~~~def~~~ghi####jkl~~~mno~~~pqr###stu~~~vwx~~~yz1";
$val=explode("####", $val);
//result will be
$valWillBe=array(3) {
[0]=>'abc~~~def~~~ghi',
[1]=>'jkl~~~mno~~~pqr',
[2]=>'stu~~~vwx~~~yz1'
}
//if you want to explode again you use a loop
for($r=0; $r<sizeof($val); $r++){
$val[$r]=explode("~~~", $val[$r]);
}
//now you have your string exploded all in places.
?>

Categories