Regular Expression to split at number with 5 digits (PHP) [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've got the following problem.
I would like to split a string at a specific place. It's used to work with a csv file.
Following situation:
My CSV File goes like this:
33333|'AB'|'01.01.2014'|'short'44444|'AB'|'01.01.2014'|'short'11111|'AB'|'01.01.2014'|'short'
This means: I've got an ID at the beginning containing 5 digits, and I want to split this string and parse it into an array. I would like to use preg_split but how could I do this? I think of matching this part:
'44444|
And now the special wish: I would like to get this 5 digits into my array. So I want to get access to the part, that preg_split splices - is this possible?
Thank you very much in advance

Is that what you want?
$str = "33333|'AB'|'01.01.2014'|'short'44444|'AB'|'01.01.2014'|'short'11111|'AB'|'01.01.2014'|'short'";
$res = preg_split('/(\b\d{5}\|)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($res);
output:
Array
(
[0] => 33333|
[1] => 'AB'|'01.01.2014'|'short'
[2] => 44444|
[3] => 'AB'|'01.01.2014'|'short'
[4] => 11111|
[5] => 'AB'|'01.01.2014'|'short'
)

You don't necessarily need regex here:
$array = explode('|', $your_csv_data);
will give you an array of the csv values. This of course only works if the pipe character cannot appear in the actual values. If you want the first item as the key for the dataset, you could do this:
$key = array_shift($array);
$list_of_csv_datas[$key] = $array;
Please correct me if I misunderstood you.

I think you are trying to split the strings according to boundary which was present just before to the 5 digit number.
<?php
$string="33333|'AB'|'01.01.2014'|'short'44444|'AB'|'01.01.2014'|'short'11111|'AB'|'01.01.2014'|'short'";
$regex = '~(?<!^)(?=\d{5})~';
$splits = preg_split($regex, $string);
print_r($splits);
?>
Output:
Array
(
[0] => 33333|'AB'|'01.01.2014'|'short'
[1] => 44444|'AB'|'01.01.2014'|'short'
[2] => 11111|'AB'|'01.01.2014'|'short'
)

This is really a parsing problem, not a regular expression problem. PHP has several built-in functions for parsing CSV data:
str_getcsv
fgetcsv
If you want to parse the entire row into an array, you can use str_getcsv() like so:
$csv = "33333|'AB'|'01.01.2014'|'short'44444|'AB'|'01.01.2014'|'short'11111|'AB'|'01.01.2014'|'short'";
$csvArray = str_getcsv($csv, "|", "'");
print_r($csvArray);
Which gives you:
Array
(
[0] => 33333
[1] => AB
[2] => 01.01.2014
[3] => short44444
[4] => AB
[5] => 01.01.2014
[6] => short11111
[7] => AB
[8] => 01.01.2014
[9] => short
)
Or, if you really just want the first column, you can just get everything on that line up until the first | delimiter:
echo substr($csv, 0, strpos($csv, '|'));

Related

String to array when two comma to one array with php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
my string has
$string = "apple,banana,orange,lemon";
I want to as
$array = [
[apple,banana],
[orange,lemon]
]
Use array_chunk in combination with explode defined in php https://www.php.net/manual/en/function.array-chunk.php
<?php
$string = "apple,banana,orange,lemon";
$input_array = explode (",", $string);
print_r(array_chunk($input_array, 2));
?>
Will output as below:
Array
(
[0] => Array
(
[0] => apple
[1] => banana
)
[1] => Array
(
[0] => orange
[1] => lemon
)
)
I hope this helps you get on your way. To transform a string to an array, you can use
$elements = explode(',', $string);
This will leave you with this array: ($elements == [apple,banana,orange,apple])
From there, you can build it the way you want, like:
$array[] = [$elements[0], $elements[1]];
$array[] = [$elements[2], $elements[3]];
This results in the array you are looking for, but this solution is only for the string you've given with four elements, separated by comma.

PHP - Converting String to Array that is already formated as an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
For clarification purposes I am using 2 separate files. So I am trying to check if a value exist within my array that is generated in my 2nd file. The first file stores the input below...
//mytxtfile.txt previous content stored in a text file using file_put_content and print_r...
Array
(
[0] => Bill
[1] => Bob
[2] => Joe
[3] => Frank
[4] => Mark
)
My 2nd file I try to call file_get_content but now realize that it stores my input as a string. Is there any way to convert this string back to an array in my new file? I have tried json_decode but it says it is null... Or if this is too much of a hassle I am also willing to change the format on how it is stored in the 1st file that generates the content.
<?php
$input = "Array
(
[0] => Bill
[1] => Bob
[2] => Joe
[3] => Frank
[4] => Mark
)";
$pattern = '/\[(?<keys>\w+)\]\s=>\s(?<values>\S+)/';
preg_match_all($pattern, $input, $matches);
$values = $matches['values'];
$keys = $matches['keys'];
$result = array_combine($keys, $values);
print_r($result);
?>
I'll explain the solution in details , but first let me post the code:
<?php //php 7.0.8
$input = "Array
(
[0] => Bill
[1] => Bob
[2] => Joe
[3] => Frank
[4] => Mark
)";
$lines = explode("\n", $input);
$values = array();
for ($i = 2; $i < count($lines) - 1; $i++) {
$value = explode("=>", $lines[$i])[1];
$value = trim($value);
array_push($values, $value);
}
print_r($values);
?>
So the file contains the formatted array as a text , we will split the content of the file into lines , this can be done using explode() function , now the $lines array contains the text rows of the file.
Now we will loop to extract the values , notice that the loop starts from $i = 2 , this because we're ignoring the first line (which contains Array) and the second line (which contains () , and the loop ends right before the last line , because we're ignoring the last line (which contains )).
We initialize an empty array $values to store the values of the array , to do this we again need to split each line using explode() function , but having in mind that the separator is => , this will return an array similar to ("[0]", " Bill") , since we want the string " Bill" we use the index 1.
Next (this step is optional) , we get rid of the whitespace before the value using the trim() function.
Finally , we push the resultant $value into the empty array.
When the loop ends you will get the extracted values.
For the sake of reference , here's the documentation of the used functions:
trim() http://php.net/manual/en/function.trim.php
explode() http://php.net/manual/en/function.explode.php
array_push() http://php.net/manual/en/function.array-push.php

Need to extract words from string in php [duplicate]

This question already has answers here:
Extract words from string with preg_match_all
(7 answers)
Closed 8 years ago.
I need to extract the names from the following string:
$contact = "John96783819Dickson97863424"
i tried using this:
preg_match('/[a-zA-Z]/',$contact,$matches);
but i get an array with all the alphabets individually in the array.
Desired Output:
Array ([0] => 'John', [2] => 'Dickson')
And now it gets complicated. The same reggae should extract this
$contact = 'Vincent Tan96123179Lawrence Thoo90603123Ryan Ong91235721'
into this
Array ([0] => 'Vincent Tan', [2] => 'Lawrance Thoo' , [3] => 'Ryan Ong')
How do i do that?
All you need is to quantify the character class using +
/[a-zA-Z]+/
+ matches one occurence of presceding regex
Example : http://regex101.com/r/bI6aH1/1
preg_match_all('/[a-zA-Z]+/',$contact,$matches);
Will give output as
Array ( [0] => John [1] => Dickson )
preg_match('/[a-zA-Z]+/',$contact,$matches);
The /[a-zA-Z]/ means match any ONE letter, anywhere in the string. Adding the + in /[a-zA-Z]+/ means match one or MORE sequential letters.

explode string one by one character including space [duplicate]

This question already has answers here:
php explode all characters [duplicate]
(4 answers)
Closed 8 years ago.
how i can explode string into an array. Acctually i want to translate english language into the braille. First thing i need to do is to get the character one by one from a string,then convert them by mathing the char from value in database and display the braille code using the pic. As example when user enter "abc ef", this will create value separately between each other.
Array
(
[0] => a
[1] => b
[2] => c
[3] =>
[4] => e
[5] => f
)
i tried to do but not get the desired output. This code separated entire string.
$papar = preg_split('/[\s]+/', $data);
print_r($papar);
I'm sorry for simple question,and if you all have an idea how i should do to translate it, feel free to help. :)
If you're using PHP5, str_split will do precisely what you're seeking to accomplish. It splits each character in a string – including spaces – into an individual element, then returns an array of those elements:
$array = str_split("abc ef");
print_r($array);
Outputs the following:
Array
(
[0] => a
[1] => b
[2] => c
[3] =>
[4] => e
[5] => f
)
UPDATE:
The PHP4 solution is to use preg_split. Pass a double forward slash as the matching pattern to delimit the split character-by-character. Then, set the PREG_SPLIT_NO_EMPTY flag to ensure that no empty pieces will be returned at the start and end of the string:
$array = preg_split('//', "abc ef", -1, PREG_SPLIT_NO_EMPTY); // Returns same array as above
PHP has a very simple method of getting the character at a specific index.
To do this, utilize the substring method and pass in the index you are looking for.
How I would approach your problem is
Ensure the string you are converting has at least a size of one
Determine how long the string is
int strlen ( string $string )
Loop over each character and do some operation depending on that character
With a string "abcdef"
$rest = substr("abcdef", -1); // returns "f"
See the substr page for a full example and more information
http://us2.php.net/substr
You can iterate the string itself.
$data = 'something string';
for($ctr = 0; $ctr < strlen($data); $ctr++)
{
if($data{$ctr}):
$kk = mysql_query("select braille_teks from braille where id_huruf = '$data{$ctr}'");
$jj = mysql_fetch_array($kk);
$gambar = $jj['braille_teks'];
?>
<img src="images/<?php echo $gambar;?>">
<?php
else:
echo "&nbsp";
}

trying to filter string with <br> tags using explode, does not work

I get a string that looks like this
<br>
ACCEPT:YES
<br>
SMMD:tv240245ce
<br>
is contained in a variable $_session['result']
I am trying to parse through this string and get the following either in an array or as separate variables
ACCEPT:YES
tv240245ce
I first tried
to explode the string using as the delimiter, and that did not work
then I already tried
$yes = explode(":", strip_tags($_SESSION['result']));
echo print_r($yes);
which gives me an array like so
Array ( [0] => ACCEPT [1] => YESSEED [2] => tv240245ce ) 1
which gives me one of my answers.
Please what would be a great way of trying to achieve what I am trying to achieve?
is there a way to get rid of the first and last?
then use the remaining one as a delimiter to explode the string ?
or what's the best way to go about this ?
This will do it:
$data=preg_split('/\s?<br>\s?/', str_replace('SMMD:','',$data), NULL, PREG_SPLIT_NO_EMPTY);
See example here:
CodePad
You can also skip caring about the spurious <br> and treat the whole string as key:value format with a simple regex like:
preg_match_all('/^(\w+):(.*)/', $text, $result, PREG_SET_ORDER);
This requires that you really have line breaks in it though. Gives you a $result list which is easy to convert into an associative array afterwards:
[0] => Array
(
[0] => ACCEPT:YES
[1] => ACCEPT
[2] => YES
)
[1] => Array
(
[0] => SMMD:tv240245ce
[1] => SMMD
[2] => tv240245ce
)
First, do a str_replace to remove all instances of "SMMD:". Then, Explode on "< b r >\n". Sorry for weird spaced, it was encoding the line break.
Include the new line character and you should get the array you want:
$mystr = str_replace( 'SMMD:', '', $mystr );
$res_array = explode( "<br>\n", $mystr );

Categories