i have a string like this one
$sitesinfo = 'site 1 titles-example1.com/
site 2 titles-example2.com/
site 3 titles-example3.com/
site 4 titles-example4.com/
site 5 titles-example5.com/';
i used to split lines into 1 array like this
$lines = explode("/",$sitesinfo);
then while i loop i got each line into an array object without problems
what i need to do to split each line into 2 pieces and add each piece into an array so the result be like this
$titles = array("site 1 titles","site 2 titles","site 3 titles","site 4 titles","site 5 titles");
$domains = array("example1.com","example2.com","example3.com","example4.com","example5.com");
so i can use them in script
i did a lot of tries but fail :(
Thanks
How about this:
foreach ($lines as $line) {
$t = explode('-', trim($line), 2);
if (count($t) < 2) {
echo "Failed to parse the line $line";
continue;
}
$titles[] = $t[0];
$domains[] = $t[1];
}
Explanation: each line split by '-' symbol into exactly 2 parts (if there's less, that's an error - the line doesn't contain '-', and thus shouldn't be processed at all). The first part is pushed into $titles array, the second - into $domains.
regex alternative:
$sitesinfo = 'site 1 titles-example1.com/
site 2 titles-example2.com/
site 3 titles-example3.com/
site 4 titles-example4.com/
site 5 titles-example5.com/';
preg_match_all('~([^-]+)-(.*)~',$sitesinfo,$matches);
$titles = array_map('trim',$matches[1]);
$domains = array_map('trim',$matches[2]);
First of all split the string into each line (by the line ending character).
Then split each line into two parts at the first - and add those parts to the result. You can later on give each part a name on it's own:
Example/Demo:
$lines = explode("\r\n", $sitesinfo);
$r = array(null, null);
foreach($lines as $line) {
list($r[0][], $r[1][]) = explode("-", $line, 2) + array(1 => NULL);
}
list($titles, $domains) = $r;
unset($r);
Or the regex variant (Demo):
preg_match_all('~([^-]+)-(.*)~', $sitesinfo, $matches);
list(, $titles, $domains) = $matches;
unset($matches);
Result:
array(5) {
[0]=>
string(13) "site 1 titles"
[1]=>
string(13) "site 2 titles"
[2]=>
string(13) "site 3 titles"
[3]=>
string(13) "site 4 titles"
[4]=>
string(13) "site 5 titles"
}
array(5) {
[0]=>
string(13) "example1.com/"
[1]=>
string(13) "example2.com/"
[2]=>
string(13) "example3.com/"
[3]=>
string(13) "example4.com/"
[4]=>
string(13) "example5.com/"
}
Related
This question already has an answer here:
Capturing text between square brackets in PHP
(1 answer)
Closed 4 years ago.
I have string like bellow
Ref ID =={1234} [201] (text message)
I want to create an array like bellow
array(
0 => 1234,
1 => 201,
2 => "text message"
)
Right now i am doing with Exploding the string method, but its took 8 lines of coding with multiple explode like bellow.
$data = array();
$str = 'Ref ID =={1234} [201] (text message)';
$bsArr1 = explode('}', $str);
$refIdArr = explode('{', $bsArr1);
$data[0] = $refIdArr[1];
$bsArr2 = explode(']', $bsArr[1]);
$codeArr = explode('[', $bsArr2[0]);
....
....
....
Is there anyway to achieve this with preg_match?
This will find one of [{( and capture all following lazy to }])
$str = "Ref ID =={1234} [201] (text message)";
preg_match_all("/[{|\[|\(](.*?)[\]|\)\}]/", $str, $matches);
var_dump($matches);
output:
array(2) {
[0]=>
array(3) {
[0]=>
string(6) "{1234}"
[1]=>
string(5) "[201]"
[2]=>
string(14) "(text message)"
}
[1]=>
array(3) {
[0]=>
string(4) "1234"
[1]=>
string(3) "201"
[2]=>
string(12) "text message"
}
}
https://3v4l.org/qKlSK
Simple pregmatch:
preg_match('/{(\d+)}.*\[(\d+)].*\(([a-zA-Z ]+)\)/', 'Ref ID =={1234} [201] (text message)', $matches);
$arr[] = $matches[1];
$arr[] = $matches[2];
$arr[] = $matches[3];
echo '<pre>';
var_dump($arr);
die();
I want if the first number in the string is 2 the output will be 2 array. How to explode as each array from string.
My code
<?php
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
$data = explode(',',$str);
$out = array();
for($i=1;$i < count($data)-1;$i++){
$out[]= explode(';',$data[$i]);
}
$i = $out[0][0];
foreach ($out as $key => $value) {
for($a=0;$a < $i; $a++){
echo $value[$a]. "<br/>";
}
}
?>
I get the result 221107-09-201607-09-201608-09-201610-09-201613
But I want this format
<?php
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
//format will be split by semicomma ;
$arr1 = Array('2','1','07-09-2016','08-09-2016','1','100.00');
$arr2 = Array('2','1','07-09-2016','10-09-2016','3','450.00');
?>
The php function array_column will come in handy here. Here is short code example that should output what you are looking for.
<?php
//Your original input
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00";
//explode the array into its sub-arrays
$arrs = explode(",", $str);
//remove the first element that sets how many elements are in each array
$numArrs = array_shift($arrs);
//convert strings into those wanted sub-arrays
array_walk($arrs, function(&$val, $key) { $val = explode(';',$val); });
//make the answer we need
$ans = array();
for($i=0; $i<$numArrs; $i++) {
//array_column does all the work that we want, making life easy
$ans[] = array_column($arrs, $i);
}
var_dump($ans);
This process does assume the string is properly formatted for what we are looking for - it will fail horribly if that is not the case.
Use the explode() function! It's really cool.
Here's how I would solve this problem. You will end up with a 2d array with my code. You can access $arr1 with $fourthStep[0] and $arr2 with $fourthStep[1] etc...
<?php
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
$fourthStep = array();
//First, let's split that string up into something a little more.. readable.
$firstStep = explode(",",$str);
//$firstStep[0] contains our count for the total array count.
foreach($firstStep as $secondStep){ //Our second step is to loop through the newly created array which splits each section of your array
if ($secondStep != $firstStep[0]){ //skip the first part, as that is only telling us of array count
$thirdStep = explode(";",$secondStep); //third step is to get each data part of each section. The count of this array should be 'firstStep[0]-1'
for($i = 0; $i<$firstStep[0]; $i++){
//Now we want to assign the values into a 2D array
$fourthStep[$i][count($fourthStep[$i])] = $thirdStep[$i];
}
}
}
var_dump($fourthStep);
?>
Result:
array(2) { [0]=> array(6) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> string(10) "07-09-2016" [3]=> string(10) "08-09-2016" [4]=> string(1) "1" [5]=> string(6) "100.00" } [1]=> array(6) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> string(10) "07-09-2016" [3]=> string(10) "10-09-2016" [4]=> string(1) "3" [5]=> string(6) "450.00" } }
Just for a further note, you don't need the '2' in the first part of your string to work out how many arrays to split it into, as they use 2 different seperators you can work it out quite easily. Save like 8 bits of space or somethin'
Lets say I have a array of 120 items. I need to separate them into comma separated texts in equal chunks.
For example if I choose to separate all elements to chunks of 50 / 120 items should be separated as 50, 50 and 20.
I tried below code:
$lines = file("all.txt", FILE_IGNORE_NEW_LINES);
$allarr[] = array_chunk($lines, 50);
foreach($allarr[0] as $chunks);
{
$str = implode($chunks,",");
echo $str."<br><br>";
}
The above code create the correct chunks of array. But When I want to loop it and add implode. It just prints the last array.
EDIT : For easy understanding below is the example
$lines = array(1,2,3,4,5);
$allarr = array_chunk($lines, 3);
var_dump($allar);
foreach($allarr as $chunks);
{
var_dump($chunks);
$str = implode($chunks,",");
}
Where $allar output is
array(2) {
[0]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
[1]=>
array(2) {
[0]=>
int(4)
[1]=>
int(5)
}
}
But $chunks output is only last part of array
array(2) {
[0]=>
int(4)
[1]=>
int(5)
}
You have an extra ; that's ending the foreach loop early.
foreach ($allarr as $chunks);
^
So you're doing nothing in the foreach loop, and then doing var_dump($chunks) after the loop is finished. That's why it only shows the last chunk.
Get rid of that ; and it will work correctly.
DEMO
OK..
I'm working blind on a "big" product web app...
We've got a couple of thousand products each with a bunch of data elements coming in from multiple vendors in various formats... so, needless to say, we can't see the data...
Here's the short version of today's problem...
We want to extract the "size" from the 'product name'
$product_name = "Socket Assembly w/ 25 ft Lamp Cord - 14 Gauge ";
and here's "part of the Sizes array....
$lookForTheseSizes = array( ...'Gallon','gal','Gal','G','Gram','gram','g','gm','Gauge','gauge'... );
The Sizes array, currently with around 100 values, is built dynamically and may change with new values added without notice.
So this script does not always work... as it is dependent on how the Sizes array values are ordered.
foreach ($lookForTheseSizes as $key => $value){
if (strpos( $nameChunk,$value) !== false) {
echo 'match '.$nameChunk.' => '.$value.'<br/>';
$size = $value;
break;
}
}
For example... when $nameChunk = "Gauge" ... the script returns a "match" on 'g' first....
So... my question is this...
Is there a way -regex or standard php 5.4 or better function- to do an extract find/match ... WITHOUT first sorting the Sizes array ?
$product_name = "Socket Assembly w/ 25 ft Lamp Cord - 14 Gauge ";
$lookForTheseSizes = array('Gallon', 'gal', 'Gal', 'G', 'Gram', 'gram', 'g',
'gm', 'Gauge', 'gauge', 'ft');
foreach($lookForTheseSizes as $unit)
{
if (preg_match('/(?P<size>[\d.]+)\s*' . preg_quote($unit) . '\b/U',
$product_name, $matches))
echo $matches['size'] . " " . $unit . "\n";
}
Result
14 Gauge
25 ft
Or..
$units = join('|' , array_map('preg_quote', $lookForTheseSizes));
if (preg_match_all('/(?P<size>[\d.]+)\s*(?P<unit>' . $units . ')\b/U',
$product_name, $matches))
var_dump($matches);
Look at $matches and do what you want.
[0]=>
array(2) {
[0]=>
string(5) "25 ft"
[1]=>
string(8) "14 Gauge"
}
["size"]=>
array(2) {
[0]=>
string(2) "25"
[1]=>
string(2) "14"
}
["unit"]=>
array(2) {
[0]=>
string(2) "ft"
[1]=>
string(5) "Gauge"
}
I would throw out the case-sensitive repeating units from the array and use additional modifier i in regex (it will be /iU instead of /U).
I have a string like as below.
$string = "height=175cm weight=70kgs age=25yrs"
String contents are key value pairs each pair are separated by a Tab. I want each key value pairs as separate variable and prints out each.
I have tried with below code but i am not getting proper result please help me where i went wrong.
$string = "height=175cm weight=70kgs age=25yrs";
$pattern = "(([^=]*)\s*=\s*(.*))";
if (preg_match($pattern,$string,$match)) {
echo "<pre>";
print_r($match);
} else {
echo "not matche\n";
}
Result:
Array
(
[0] => height=175cm weight=70kgs age=25yrs
[1] => height
[2] => 175cm weight=70kgs age=25yrs
)
You can use this code:
$string = "height=175cm weight=70kgs age=25yrs";
if (preg_match_all('/\s*([^=]+)=(\S+)\s*/', $string, $matches)) {
$output = array_combine ( $matches[1], $matches[2] );
print_r($output);
}
OUTPUT:
Array
(
[height] => 175cm
[weight] => 70kgs
[age] => 25yrs
)
You can use this:
$string = "height=175cm weight=70kgs age=25yrs";
$pattern = "/(\w+)=(\d+)(\w+)/i";
if(preg_match_all($pattern,$string,$match))
{
var_dump($match);
}
Result:
array(4) {
[0]=>
array(3) {
[0]=>
string(12) "height=175cm"
[1]=>
string(12) "weight=70kgs"
[2]=>
string(9) "age=25yrs"
}
[1]=>
array(3) {
[0]=>
string(6) "height"
[1]=>
string(6) "weight"
[2]=>
string(3) "age"
}
[2]=>
array(3) {
[0]=>
string(3) "175"
[1]=>
string(2) "70"
[2]=>
string(2) "25"
}
[3]=>
array(3) {
[0]=>
string(2) "cm"
[1]=>
string(3) "kgs"
[2]=>
string(3) "yrs"
}
}
I've pasted a code sample below which helps you to solve your problem. Certainly, it is not very tightly compressed and has quite a few more lines of code than the other answers (which are all good answers!).
The reason I did this was because it looks like you may benefit from an explanation that takes you one step at a time in the progression of solving your problem, so that you can understand what is happening along the way.
Here's the code you can use:
<?php
$string = "height=175cm\tweight=70kgs\tage=25yrs";
// Divide your string into an array, with each element
// in the array being a string with a key-value pair
$pairs = explode("\t", $string);
// See what the array of pair strings looks like.
// print_r($pairs);
// Create an array to get it ready to hold key-value pairs.
$results = array();
// For each string in your array, split at the equal sign
// and set values in the $results array.
foreach ($pairs as $pair) {
$exploded_pair = explode("=", $pair);
// See what each exploded pair array looks like.
// print_r($exploded_pair);
$key = $exploded_pair[0];
$value = $exploded_pair[1];
$results[$key] = $value;
}
print_r($results);
Instead of using regular expressions, this makes use of the explode function in PHP. You can read the documentation on explode found here.
You said that your input string is separated by tabs, which is why the assignment statement for $string has \t instead of spaces. If you were to use spaces instead of tabs, then make sure that you change
$pairs = explode("\t", $string);
to
$pairs = explode(" ", $string);