Not sure how I would do this but if someone could point me in the right track that'll be great, basically I've got a lone line of text in a variable which looks like this:
Lambo 1; Trabant 2; Car 3;
Then I want to split "Lambo" to it's own variable then "1" to it's own variable, and repeat for the others. How would I go and do this?
I know about explode() but not sure how I would do it to split the variable up twice etc.
As requested in the comments my desired output would be like this:
$Item = "Lambo"
$Quantity = 1
Then echo them out and go back to top of loop for example and do the same for the Trabant and Car
<?php
$in = "Lambo 1; Trabant 2; Car 3;";
foreach (explode(";", $in) as $element) {
$element = trim($element);
if (strpos($element, " ") !== false ) {
list($car, $number) = explode(" ", $element);
echo "car: $car, number: $number";
}
}
You can use explode to split the input on each ;, loop over the results and then split over each .
You can use preg_split and iterate over the array by moving twice.
$output = preg_split("/ (;|vs) /", $input);
You could use preg_match_all for getting those parts:
$line = "Lambo 1; Trabant 2; Car 3;";
preg_match_all("/[^ ;]+/", $line, $matches);
$matches = $matches[0];
With that sample data, the $matches array will look like this:
Array ( "Lambo", "1", "Trabant", "2", "Car", "3" )
$new_data="Lambo 1;Trabant 2;Car 3;" ;
$new_array=explode(";", $new_data);
foreach ($new_array as $key ) {
# code...
$final_data=explode(" ", $key);
if(isset($final_data[0])){ echo "<pre>".$final_data[0]."</pre>";}
if(isset($final_data[1])){echo "<pre>".$final_data[1]."</pre>";}
}
This places each word and number in a new key of the array if you need to acess them seperatly.
preg_match_all("/(\w+) (\d+);/", $input_lines, $output_array);
Click preg_match_all
http://www.phpliveregex.com/p/fM8
Use a global regular expression match:
<?php
$subject = 'Lambo 1; Trabant 2; Car 3;';
$pattern = '/((\w+)\s+(\d+);\s?)+/Uu';
preg_match_all($pattern, $subject, $tokens);
var_dump($tokens);
The output you get is:
array(4) {
[0] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[1] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[2] =>
array(3) {
[0] =>
string(5) "Lambo"
[1] =>
string(7) "Trabant"
[2] =>
string(3) "Car"
}
[3] =>
array(3) {
[0] =>
string(1) "1"
[1] =>
string(1) "2"
[2] =>
string(1) "3"
}
}
In there the elements 2 and 3 hold exactly the tokens you are looking for.
Related
How can I split this string into two arrays in PHP? The string may have many items in it.
$str = "20x9999,24x65,40x5";
I need to get two arrays from this string:
$array1 = array(20,24,40);
$array2 = array(9999,65,5);
I've tried many implementations of preg_split, slice, regex. I can't get it done... I need help!
You can explode the string by commas, and then explode each of those values by x, inserting the result values from that into the two arrays:
$str = "20x9999,24x65,40x5";
$array1 = array();
$array2 = array();
foreach (explode(',', $str) as $xy) {
list($x, $y) = explode('x', $xy);
$array1[] = $x;
$array2[] = $y;
}
Alternatively, you can use preg_match_all, matching against the digits either side of the x:
preg_match_all('/(\d+)x(\d+)/', $str, $matches);
$array1 = $matches[1];
$array2 = $matches[2];
In both cases the output is:
Array
(
[0] => 20
[1] => 24
[2] => 40
)
Array
(
[0] => 9999
[1] => 65
[2] => 5
)
Demo on 3v4l.org
I guess with preg_split, we could do so:
$str = '20x9999,24x65,40x5';
$array1 = $array2 = array();
foreach (preg_split("/,/", $str, -1, PREG_SPLIT_NO_EMPTY) as $key => $value) {
$val = preg_split("/x/", $value, -1, PREG_SPLIT_NO_EMPTY);
array_push($array1, $val[0]);
array_push($array2, $val[1]);
}
var_dump($array1);
var_dump($array2);
Output
array(3) {
[0]=>
string(2) "20"
[1]=>
string(2) "24"
[2]=>
string(2) "40"
}
array(3) {
[0]=>
string(4) "9999"
[1]=>
string(2) "65"
[2]=>
string(1) "5"
}
I'm trying to split a variable at every character, but I ran across this error:
Warning: str_split() expects parameter 2 to be long, string
The code is:
$split = str_split($num, "");
With $num being taken from the url, which only consist of numbers.
How can fix this?
The second parameter should be a number like this
<?php
$num = 100;
$split = str_split($num, 1);
print_r($split);
RESULT:
Array
(
[0] => 1
[1] => 0
[2] => 0
)
In fact you can leave the second parameter out if it is a 1 like this
<?php
$num = 100;
$split = str_split($num);
print_r($split);
And you will get the same result
As you said split a variable at every character you can just run
$split = str_split($num);
Make sure $num in not empty
Syntax str_split(string,length)
Example
<?php
print_r(str_split("1234"));
?>
Outputs - Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
You can use this:
$splitText = 1223;
$split = str_split((string) $splitText); //only on php 7
var_dump($split);
you will get this:
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "2"
[3]=>
string(1) "3"
}
Usage: array str_split ( string $string [, int $split_length = 1 ] ), but check the manual.
Below string I need to split. I tried with the explode(), but it is fragmenting the url substring.
$link = "7_5_7_http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov_00:00:09";
$ex_link = explode('_',$link);
It is splitting the string after every "_' symbol, but I need to the results like this:
$ex_link[0] = '7';
$ex_link[1] = '5';
$ex_link[2] = '7';
$ex_link[3] = 'http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov';
$ex_link[2] = '00:00:09';
Explode has a third parameter, why do people complicate things ?
$link = "7_5_7_http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov_00:00:09";
$array = explode('_', $link, 4);
$temp = array_pop($array);
$array = array_merge($array, array_reverse(array_map('strrev', explode('_', strrev($temp), 2)))); // Now it has just become complexer (facepalm)
print_r($array);
Output:
Array
(
[0] => 7
[1] => 5
[2] => 7
[3] => http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov
[4] => 00:00:09
)
Online demo
Use
preg_match('/(\d)_(\d)_(\d)_([\w:\.\/\/\-]+)_([\d]{2}:[\d]{2}:[\d]{2})/', $link, $matches);
And $matches:
array(6) {
[0]=>
string(95) "7_5_7_http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov_00:00:09"
[1]=>
string(1) "7"
[2]=>
string(1) "5"
[3]=>
string(1) "7"
[4]=>
string(80) "http://test.com/folder/images/7_newim/5_car/7_february2013/p/a00/p01/video-1.mov"
[5]=>
string(8) "00:00:09"
}
This one is simplest one
$result = preg_split('%_(?=(\d|http://))%si', $subject);
I'm having a lot of issues with matching all items that are in brackets.
Here is some code, what I need the matches to do is output something like
Array ( [0] => username [1] => id )
some code to give you an idea
$ur = '/account/{username}/{id}';
if(preg_match('', $str, $matches)){
print_r($matches);
}
How can I accomplish this?
$ur = '/account/{username}/{id}';
preg_match_all('/\{([a-z]+)\}/',$ur,$m);
echo '<pre>';
var_dump($m[1]);
output:
array(2) {
[0]=>
string(8) "username"
[1]=>
string(2) "id"
}
How can I explode a string on every third semicolon (;)?
example data:
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
Desired output:
$output[0] = 'piece1;piece2:piece3;'
$output[1] = 'piece4;piece5;piece6;'
$output[2] = 'piece7;piece8;'
I am sure you can do something slick with regular expressions, but why not just explode the each semicolor and then add them three at a time.
$tmp = explode(";", $string);
$i=0;
$j=0;
foreach($tmp as $piece) {
if(! ($i++ %3)) $j++; //increment every 3
$result[$j] .= $piece;
}
Easiest solution I can think of is:
$chunks = array_chunk(explode(';', $input), 3);
$output = array_map(create_function('$a', 'return implode(";",$a);'), $chunks);
Essentially the same solution as the other ones that explode and join again...
$tmp = explode(";", $string);
while ($tmp) {
$output[] = implode(';', array_splice($tmp, 0, 3));
};
$string = "piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;piece9;";
preg_match_all('/([A-Za-z0-9\.]*;[A-Za-z0-9\.]*;[A-Za-z0-9\.]*;)/',$string,$matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => piece1;piece2;piece3;
[1] => piece4;piece5;piece6;
[2] => piece7;piece8;piece9;
)
[1] => Array
(
[0] => piece1;piece2;piece3;
[1] => piece4;piece5;piece6;
[2] => piece7;piece8;piece9;
)
)
Maybe approach it from a different angle. Explode() it all, then combine it back in triples. Like so...
$str = "1;2;3;4;5;6;7;8;9";
$boobies = explode(";", $array);
while (!empty($boobies))
{
$foo = array();
$foo[] = array_shift($boobies);
$foo[] = array_shift($boobies);
$foo[] = array_shift($boobies);
$bar[] = implode(";", $foo) . ";";
}
print_r($bar);
Array
(
[0] => 1;2;3;
[1] => 4;5;6;
[2] => 7;8;9;
)
Here's a regex approach, which I can't say is all too good looking.
$str='';
for ($i=1; $i<20; $i++) {
$str .= "$i;";
}
$split = preg_split('/((?:[^;]*;){3})/', $str, -1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
Output:
Array
(
[0] => 1;2;3;
[1] => 4;5;6;
[2] => 7;8;9;
[3] => 10;11;12;
[4] => 13;14;15;
[5] => 16;17;18;
[6] => 19;
)
Another regex approach.
<?php
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8';
preg_match_all('/([^;]+;?){1,3}/', $string, $m, PREG_SET_ORDER);
print_r($m);
Results:
Array
(
[0] => Array
(
[0] => piece1;piece2;piece3;
[1] => piece3;
)
[1] => Array
(
[0] => piece4;piece5;piece6;
[1] => piece6;
)
[2] => Array
(
[0] => piece7;piece8
[1] => piece8
)
)
Regex Split
$test = ";2;3;4;5;6;7;8;9;10;;12;;14;15;16;17;18;19;20";
// match all groups that:
// (?<=^|;) follow the beginning of the string or a ;
// [^;]* have zero or more non ; characters
// ;? maybe a semi-colon (so we catch a single group)
// [^;]*;? again (catch second item)
// [^;]* without the trailing ; (to not capture the final ;)
preg_match_all("/(?<=^|;)[^;]*;?[^;]*;?[^;]*/", $test, $matches);
var_dump($matches[0]);
array(7) {
[0]=>
string(4) ";2;3"
[1]=>
string(5) "4;5;6"
[2]=>
string(5) "7;8;9"
[3]=>
string(6) "10;;12"
[4]=>
string(6) ";14;15"
[5]=>
string(8) "16;17;18"
[6]=>
string(5) "19;20"
}
<?php
$str = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
$arr = array_map(function ($arr) {
return implode(";", $arr);
}, array_chunk(explode(";", $str), 3));
var_dump($arr);
outputs
array(3) {
[0]=>
string(20) "piece1;piece2;piece3"
[1]=>
string(20) "piece4;piece5;piece6"
[2]=>
string(14) "piece7;piece8;"
}
Similar to #Sebastian's earlier answer, I recommend preg_split() with a repeated pattern. The difference is that by using a non-capturing group and appending \K to restart the fullstring match, you can spare writting the PREG_SPLIT_DELIM_CAPTURE flag.
Code: (Demo)
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
var_export(preg_split('/(?:[^;]*;){3}\K/', $string, 0, PREG_SPLIT_NO_EMPTY));
A similar technique for splitting after every 2 things can be found here. That snippet actually writes the \K before the last space character so that the trailing space is consumed while splitting.