split text by words and punctuation marks - php

I have this text:
A man’s jacket is of green color. He – the biggest star in modern history – rides bikes very fast (230 km per hour). How is it possible?! What kind of bike is he using? The semi-automatic gear of his bike, which is quite expensive, significantly helps to reach that speed. Some (or maybe many) claim that he is the fastest in the world! “I saw him ride the bike!” Mr. John Deer speaks. “The speed he sets is 133.78 kilometers per hour,” which sounds incredible; sounds deceiving.
I want to have the following resulting array:
words[1] = "A"
words[2] = "man's"
words[3] = "jacket"
...
words[n+1] = "color"
words[n+2] = "."
words[n+3] = "He"
words[n+4] = "-"
words[n+5] = "the"
...
This array should include all words and punctuation marks separately. Can that be performed using regexp? Can anyone help to compose it?
Thanks!
EDIT: based on request to show my work.
I'm processing the text using the following function, but I want to do the same in regex:
$text = explode(' ', $this->rawText);
$marks = Array('.', ',', ' ?', '!', ':', ';', '-', '--', '...');
for ($i = 0, $j = 0; $i < sizeof($text); $i++, $j++) {
$skip = false;
//check if the word contains punctuation mark
foreach ($marks as $value) {
$markPosition = strpos($text[$i], $value);
//if contains separate punctation mark from the word
if ($markPosition !== FALSE) {
//check position of punctation mark - if it's 0 then probably it's punctuation mark by itself like for example dash
if ($markPosition === 0) {
//add separate mark to array
$words[$j] = new Word($j, $text[$i], 2, $this->phpMorphy);
} else {
$words[$j] = new Word($j, substr($text[$i], 0, strlen($text[$i]) - 1), 0, $this->phpMorphy);
//add separate mark to array
$punctMark = substr($text[$i], -1);
$j += 1;
$words[$j] = new Word($j, $punctMark, 1, $this->phpMorphy);
}
$skip = true;
break;
}
}
if (!$skip) {
$words[$j] = new Word($j, $text[$i], 0, $this->phpMorphy);
}
}

The following will split on your specific text.
$words = preg_split('/(?<=\s)|(?<=\w)(?=[.,:;!?()-])|(?<=[.,!()?\x{201C}])(?=[^ ])/u', $text);
See working demo

Try making use of preg_split. Pass your punctuations(of your choice) inside the square brackets [ and ]
<?php
$str="A man’s jacket is of green color. He – the biggest star in modern history – rides bikes very fast (230 km per hour). How is it possible?! What kind of bike is he using? The semi-automatic gear of his bike, which is quite expensive, significantly helps to reach that speed. Some (or maybe many) claim that he is the fastest in the world! “I saw him ride the bike!” Mr. John Deer speaks. “The speed he sets is 133.78 kilometers per hour,” which sounds incredible; sounds deceiving.";
$keywords=preg_split("/[-,. ]/", $str);
print_r($keywords);
OUTPUT:
Array (
[0] => A
[1] => man’s
[2] => jacket
[3] => is
[4] => of
[5] => green
[6] => color
[7] =>
[8] => He
[9] => –
[10] => the
[11] => biggest
[12] => star
[13] => in
[14] => modern
[15] => history
[16] => –
Message truncated to prevent abuse of resources ... Shankar ;)

Related

Operation on String - Substrings: Get Positions and Count

I have a problem with operations on a string in PHP, I have one string like this:
$words = "Ala ma kota a kot ma ale";
How do I get the number of appearances of al in this long string $words? Additionally, I need the index of the beginning of all appearances of al.
$count = substr_count($words, 'al');
I tried it with the substr_count(), but it only returned the count. I need the index of the appearance as well.
EDIT Adding expected output:
number of al: 2, at index: 0, at index: 22
This is easily accomplished with preg_match_all() using PREG_OFFSET_CAPTURE flag:
$words = "Ala ma kota a kot ma ale. All in Valhalla shall recall the fall.";
preg_match_all('~(al)~i', $words, $matches, PREG_OFFSET_CAPTURE);
print_r($matches[1]);
See a live demo at https://3v4l.org/Frsa5. We have the i modifier for case-insensitive matching. If you want case-sensitive matching, remove it. If you want only als at the start of words, use \bal (\b = word boundary). The result is an array with matches and offsets, as follows:
Array [
[0] => [
[0] => Al
[1] => 0
]
[1] => [
[0] => al
[1] => 21
]
[2] => [
[0] => Al
[1] => 26
]
[3] => [
[0] => al
[1] => 34
]
[4] => [
[0] => al
[1] => 37
]
[5] => [
[0] => al
[1] => 44
]
[6] => [
[0] => al
[1] => 51
]
[7] => [
[0] => al
[1] => 60
]
]
Edit: Since there's nothing else being matched, you don't really need the (al) capture group. You can also just remove the brackets, match ~al~i, and get the results in $matches[0] (containing full pattern matches). I've left it as is with the capture group in place, in case you may want to use more complex matching rules in the future (& being lazy to update the demo).
You could build a loop that continuously searches the array, until you run out of count, probably. Or you could wing it and make a loop that continuously does strpos() and count it in the end. Note that you need to somehow make sure you're not checking the same position over and over, that's what the $position++ is there in this piece of code.
Here, this will output exactly what you asked for in the comment, with the correct position that is. (I didn't see the comment before)
$position = 0;
$words = strtolower("Ala ma kota a kot ma ale");
$needle = 'al';
$positions = [];
do {
$position = strpos($words, $needle, $position);
if ($position !== false) {
array_push($positions, $position);
$position++;
}
} while ($position);
echo 'number of al: '.count($positions);
foreach ($positions as $position) {
echo ', at index: '.$position;
}
Output:
number of al: 2, at index: 0, at index: 21
Edit: As noted by eis, this could be simplified down to
<?php
$position = 0;
$words = strtolower("Ala ma kota a kot ma alet ma ale");
$needle = 'al';
$positions = [];
$position = -1;
while (($position = strpos($words, $needle, $position + 1)) !== false) {
array_push($positions, $position);
}
echo 'number of al: ' . count($positions);
foreach ($positions as $position) {
echo ', at index: ' . $position;
}
Edit: As Markus AO said, you might want to base your position movement (position++;) on the length of the needle. I think that depends on the way you wish to match.
a) If you want to match all appearances (aba → abababa = 3 ... match may occur within the previous match,) keep it this way.
b) If you want to match all 'full' appearances (aba → abababa = 2,) increment the position by the needle's length.

Replace first character of sting in PHP with rules

I'm wanting to replace the first character of a string with a specific character depending on its value,
A = 0
B = 1
C = 2
Is there a way to do this based on rules? In total I will have 8 rules.
Ok, so I'm editing this to add more information as I don't think some people understand / want to help without the full picture...
My string will be any length between 5 and 10 characters
Capitals will not factor into this, it is not case sensitive
Currently there is no code, I'm not sure the best way to do this. I can write an if statement on a substring, but I know straight away that is inefficient.
Below is the before and after that I am expecting, I have kept these examples simple but all I am looking to do is replace the first character with a specific character depending on its value. For now, there are eight rules, but this could grow in the future
INPUT OUTPUT
ANDREW 1NDREW
BRIAN 2RIAN
BOBBY 2OBBY
CRAIG 3RAIG
DAVID 4AVID
DUNCAN 4UNCAN
EDDIE 5DDIE
FRANK 6RANK
GEOFF 7EOFF
GIANA 7IANA
HAYLEY 8AYLEY
So as you can see, pretty straight forward, but is there a simple way to specifically specify what a character should be replaced by?
Assuming all the rules are for single characters, like in the example, it would be easisest to code them in to a dictionary:
$rules = array('A' => 0, 'B' => 0 /* etc... */);
$str[0] = $rules[$str[0]];
I think this is what you want.
<?php
$input = array('ANDREW','BRIAN','BOBBY','CRAIG','DAVID','DUNCAN','EDDIE','FRANK','GEOFF','GIANA','HAYLEY');
$array = range('A','Z');
$array = array_flip(array_filter(array_merge(array(0), $array)));
$output = [];
foreach($input as $k=>$v){
$output[] = $array[$v[0]].substr($v, 1);
}
print_r($output);
?>
Output:
Array (
[0] => 1NDREW
[1] => 2RIAN
[2] => 2OBBY
[3] => 3RAIG
[4] => 4AVID
[5] => 4UNCAN
[6] => 5DDIE
[7] => 6RANK
[8] => 7EOFF
[9] => 7IANA
[10] => 8AYLEY
)
DEMO: https://3v4l.org/BHLPk

PHP separate string by specific array of words

I've array in php with following values
Array
(
[0] => Clarithromycin 250mg/5ml oral susptake TWO 5ml spoonsful TWICE each day DISCARD REMAINING AFTER TEN DAYSSHAKE THE BOTTLE WELL BEFORE USING.SPACE THE DOSES EVENLY. KEEP TAKING UNTIL THE COURSE IS FINISHED, UNLESS YOU ARE TOLD TO STOP.
[1] => Lactulose 3.1-3.7g/5ml oral solntake ONE to FOUR 5ml spoonsful TWICE each day when required (PRN : to be taken when necessary)
[2] => Mirtazapine orodisp 30mg tabsOne To Be Taken At NightALLOW THE TABLETS TO DISSOLVE ON YOUR TONGUE, THEN SWALLOW WITH THE SALIVA. TAKE AFTER FOOD.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.
[3] => Senna 7.5mg/5ml oral soln SFTwo 5ml Spoonfuls To Be Taken At NightSHAKE THE BOTTLE WELL BEFORE USING.THIS MEDICINE MAY COLOUR YOUR URINE. THIS IS HARMLESS.
[4] => SUDOCREM ANTISEPTIC HEALING CREAMas directedFOR EXTERNAL USE ONLY. (MD mean As directed)
[5] => CIRCADIN MR 2MG TABSOne To Be Taken At NightSWALLOW WHOLE. DO NOT CHEW OR CRUSH.TAKE WITH OR JUST AFTER FOOD, OR A MEAL.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.
[6] => Memantine 10mg tabsOne To Be Taken Each Day
[7] => Omeprazole gr 10mg capsOne To Be Taken Each DaySWALLOW WHOLE.DO NOT CHEW OR CRUSH.
[8] => Senna 7.5mg tabsTwo To Be Taken At NightTHIS MEDICINE MAY COLOUR YOUR URINE. THIS IS HARMLESS.
)
I wanna separate medicine and description by specific words. e.g (take two,one to be taken,one to,to be taken etc.....)
array
(
[0] => Array
(
[medicine] => Clarithromycin 250mg/5ml oral susp
[description] => take TWO 5ml spoonsful TWICE each day DISCARD REMAINING AFTER TEN DAYSSHAKE THE BOTTLE WELL BEFORE USING.SPACE THE DOSES EVENLY. KEEP TAKING UNTIL THE COURSE IS FINISHED, UNLESS YOU ARE TOLD TO STOP.
)
[1] => Array
(
[medicine] => Lactulose 3.1-3.7g/5ml oral soln
[description] =>take ONE to FOUR 5ml spoonsful TWICE each day when required (PRN : to be taken when necessary)
)
[2] => Array
(
[medicine] => Mirtazapine orodisp 30mg tabs
[description] => One To Be Taken At NightALLOW THE TABLETS TO DISSOLVE ON YOUR TONGUE, THEN SWALLOW WITH THE SALIVA. TAKE AFTER FOOD.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.
)
.
.
.
.
)
try this:
foreach ($array as $key => $value) {
$explode = explode('separate', $value);
$array[$key] = array(
'medicine' => $explode[0],
'description' => $explode[1]
);
}
just edit 'separate' by the word you want to seperate your text with
//Main array
//Create array of words that you have to separate from
$arrOfsplittedData = [];
$intCount = 0;
foreach($arrOfMedicineAndDesc as $medicineAndDesc){
$lowerCaseMedicineAndDesc = strtolower($medicineAndDesc);
$splitMedicineAndDesc = multiexplode(array("oral", "tabsone", "cream", "capsone", "tabstwo"), $lowerCaseMedicineAndDesc);
if($splitMedicineAndDesc){
$arrOfsplittedData[$intCount]["medicine"] = $splitMedicineAndDesc[0];
$arrOfsplittedData[$intCount]["description"] = $splitMedicineAndDesc[1];
}
$intCount++;
}
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
echo "<pre>";
print_r($arrOfsplittedData);die;
You can be crafty with regex to do this:
<?php
$array = array(
"Clarithromycin 250mg/5ml oral susptake TWO 5ml spoonsful TWICE each day DISCARD REMAINING AFTER TEN DAYSSHAKE THE BOTTLE WELL BEFORE USING.SPACE THE DOSES EVENLY. KEEP TAKING UNTIL THE COURSE IS FINISHED, UNLESS YOU ARE TOLD TO STOP.",
"Lactulose 3.1-3.7g/5ml oral solntake ONE to FOUR 5ml spoonsful TWICE each day when required (PRN : to be taken when necessary)",
"Mirtazapine orodisp 30mg tabsOne To Be Taken At NightALLOW THE TABLETS TO DISSOLVE ON YOUR TONGUE, THEN SWALLOW WITH THE SALIVA. TAKE AFTER FOOD.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.",
"Senna 7.5mg/5ml oral soln SFTwo 5ml Spoonfuls To Be Taken At NightSHAKE THE BOTTLE WELL BEFORE USING.THIS MEDICINE MAY COLOUR YOUR URINE. THIS IS HARMLESS.",
"SUDOCREM ANTISEPTIC HEALING CREAMas directedFOR EXTERNAL USE ONLY. (MD mean As directed)",
"CIRCADIN MR 2MG TABSOne To Be Taken At NightSWALLOW WHOLE. DO NOT CHEW OR CRUSH.TAKE WITH OR JUST AFTER FOOD, OR A MEAL.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.",
"Memantine 10mg tabsOne To Be Taken Each Day",
"Omeprazole gr 10mg capsOne To Be Taken Each DaySWALLOW WHOLE.DO NOT CHEW OR CRUSH.",
"Senna 7.5mg tabsTwo To Be Taken At NightTHIS MEDICINE MAY COLOUR YOUR URINE. THIS IS HARMLESS."
);
$splitWords = [
"take \w+?\b",
"to be taken"
]; //Regex of what you want to split on
$regex = "/(".implode("|",$splitWords).")/";
$replaced = preg_replace($regex, "\n$1", $array); //Replace what you found with a newline + what you found
print_r(array_map(function ($v) {
$array = explode("\n",$v);
return [
"medicine" => $array[0],
"description" => isset($array[1])?$array[1]:null
]; //If you're array is bigger than 2 elements you may need to loop here.
},$replaced)); //Split sentences on the newlines.
Here's an example:
http://sandbox.onlinephpfunctions.com/code/b2e2ceef17152e9a888a7b68fab3acb2e9f10fe3

splitting string into php array

I have an array that outputs the following:
Array
(
[0] => #EXTM3U
[1] => #EXTINF:206,"Weird" Al Yankovic - Dare to be Stupid
[2] => E:\Dare to be Stupid.mp3
[3] => #EXTINF:156,1910 Fruitgum Company - Chewy, Chewy
[4] => E:\Chewy Chewy.mp3
[5] => #EXTINF:134,1910 Fruitgum Company - Goody Goody Gumdrops
[6] => E:\Goody Goody Gumdrops.mp3
[7] => #EXTINF:134,1910 Fruitgum Company - Simon Says
[8] => E:\Simon Says.mp3
[9] => #EXTINF:255,3 Doors Down - When I'm Gone
[10] => E:\When I'm Gone.mp3 [
11] => #EXTINF:179,? And the Mysterians - 96 Tears**
)
I need to split this array then loop through and save each value to the database, e.g:
"Weird" Al Yankovic - Dare to be Stupid
Fruitgum Company - Chewy, Chewy
Save each value above to database individually.
Thanks in advance!
Edit: Added from the comments
Let me try and explain in more detail. I start with a string that looks like this:
#EXTM3U #EXTINF:266,10cc - Dreadlock Holiday
D:\Music - Sorted\Various Artists\De Beste Pop Klassiekers Disc 1\10cc - Dreadlock Holiday.mp3
#EXTINF:263,1919 - Cry Wolf
D:\Music - Sorted\Various Artists\Gothic Rock, Vol. 3 Disc 2\1919 - Cry Wolf.mp3
#EXTINF:318,3 Doors Down - [Untitled Hidden Track]
D:\Music - Sorted\3 Doors Down\Away From The Sun\3 Doors Down - [Untitled Hidden Track].mp3
I'm then trying to strip everything out of this and just have an array of track titles, this is a playlist file for online radio. What I am doing so far:
$finaloutput = $_POST['thestring'];
$finaloutput = str_replace('#EXTINF:','',$finaloutput);
$finaloutput = str_replace('#EXTM3U','',$finaloutput);
$finaloutput = preg_split("/\r\n|\r|\n/", $finaloutput);
foreach ($finaloutput as $value) {
echo $value; echo '<br>';
}
But I still have these rows remaining, I need to try and do a str_replace between a line break and the end .mp3
D:\Music - Sorted\3 Doors Down\Away From The Sun\3 Doors Down - [Untitled Hidden Track].mp3
You can extract the relevant parts from source by use of preg_match_all with a regex like this.
$pattern = '/^#[^,\n]+,\K.*/m';
^ anchor matches start of line in multiline mode which is set with m flag.
#[^,\n]+, matches the part from # until , by use of a negated class.
\K is used to reset beginning of the reported match. We don't want the previous part.
.* the part to be extracted: Any amount of any character until end of the line.
if(preg_match_all($pattern, $finaloutput, $out) > 0);
print_r($out[0]);
PHP demo at eval.in

Writing a simple regular expression statement [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm looking for help writing a regular expression with PHP. Coming in I have the data as follows:
3 1/2 cups peeled and diced potatoes
1/3 cup diced celery
1/3 cup finely chopped onion
2 tablespoons chicken bouillon granules
I have this all in a single variable. I now am parsing it out so that it stores as 3 different usable data items.
I've not ever written a regular expression before, and I found this guide here - http://www.noupe.com/php/php-regular-expressions.html but I'm still struggling to take that and apply it to my situation. I also do not know how many rows will be coming in, it could be 1 or it could be 100.
This is what I have so far. I have tested the code around the preg_match statement and it's working.
preg_match_all("",
$post_meta,
$out, PREG_PATTERN_ORDER);
What should I put between the "" in the preg_match_all statement to achieve the desired parsing? Thanks upfront for any help you can give!
EDIT
the desired output for the example input would be:
$var1 = 3 1/2
$var2 = cups
$var3 = peeled and diced potatoes
so then I can run functions to store the data:
update_database($var1);
update_database($var2);
update_database($var3);
repeat for each row. It doesn't have to be 3 different variables, an array would be fine too.
You can break it apart with an expression like this:
$string = '3 1/2 cups peeled and diced potatoes
1/3 cup diced celery
1/3 cup finely chopped onion
2 tablespoons chicken bouillon granules';
preg_match_all('~([0-9 /]+)\s+(cup|tablespoon)s?\s+([-A-Z ]+)~i', $string, $matches);
That will give you this if you print $matches:
Array
(
[0] => Array
(
[0] => 3 1/2 cups peeled and diced potatoes
[1] => 1/3 cup diced celery
[2] => 1/3 cup finely chopped onion
[3] => 2 tablespoons chicken bouillon granules
)
[1] => Array
(
[0] => 3 1/2
[1] => 1/3
[2] => 1/3
[3] => 2
)
[2] => Array
(
[0] => cup
[1] => cup
[2] => cup
[3] => tablespoon
)
[3] => Array
(
[0] => peeled and diced potatoes
[1] => diced celery
[2] => finely chopped onion
[3] => chicken bouillon granules
)
)
Although this part isn't really necessary, you can restructure the array to put each item in the format you are asking for. (You can write to the db without putting them in this order, but I will demonstrate here how to put them into the order you are looking for.)
$info_array = array();
for ($i = 0; $i < count($matches); $i++) {
for ($j = 1; $j < count($matches[$i]); $j++) {
$info_array[$i][] = $matches[$j][$i];
}
}
If you printed $info_array, you'd see this:
Array
(
[0] => Array
(
[0] => 3 1/2
[1] => cup
[2] => peeled and diced potatoes
)
[1] => Array
(
[0] => 1/3
[1] => cup
[2] => diced celery
)
[2] => Array
(
[0] => 1/3
[1] => cup
[2] => finely chopped onion
)
[3] => Array
(
[0] => 2
[1] => tablespoon
[2] => chicken bouillon granules
)
)
You can now loop through that array to put the items into the database:
for ($i = 0; $i < count($info_array); $i++) {
foreach ($info_array[$i] AS $ingredient) {
// INSERT INTO DATABASE HERE
print "<BR>update_database(".$ingredient.")";
}
}
So that would do what you are asking, but I'm assuming that you have some columns that you want to assign these to. You can do something like this if you want to put each piece into its own column:
$info_array = array();
for ($i = 0; $i < count($matches); $i++) {
for ($j = 1; $j < count($matches[$i]); $j++) {
if ($j == 1) {$key = 'amount';}
elseif ($j == 2) {$key = 'size';}
elseif ($j == 3) {$key = 'ingredient';}
$info_array[$i][$key] = $matches[$j][$i];
}
}
print "<PRE><FONT COLOR=ORANGE>"; print_r($info_array); print "</FONT></PRE>";
for ($i = 0; $i < count($info_array); $i++) {
foreach ($info_array[$i] AS $ingredient) {
print "<BR>update_database(".$ingredient.")";
}
}
foreach ($info_array AS $ingredient_set) {
$sql = "INSERT INTO table SET Amount = '".$ingredient_set['amount']."', Size = '".$ingredient_set['size']."', Ingredient = '".$ingredient_set['ingredient']."'";
print "<BR>".$sql;
}
That would give you something like this:
INSERT INTO table SET Amount = '3 1/2', Size = 'cup', Ingredient = 'peeled and diced potatoes'
INSERT INTO table SET Amount = '1/3', Size = 'cup', Ingredient = 'diced celery'
INSERT INTO table SET Amount = '1/3', Size = 'cup', Ingredient = 'finely chopped onion'
INSERT INTO table SET Amount = '2', Size = 'tablespoon', Ingredient = 'chicken bouillon granules'
EDIT: Explanation of the REGEX
([0-9 /]+) \s+ (cup|tablespoon)s? \s+ ([-A-Z ]+)
^ ^ ^ ^ ^
1 2 3 4 5
([0-9 /]+) Looking for a digit here to capture the amount of whatever measurement you will need. The [0-9] is a character class that means only grab numbers falling between 0 and 9. Also inside the character class, I added a space and a forward slash to accomodate measurements like 3 1/2. The + sign means that it has to have at least one of those to make the match. Finally, the parenthesis around this part tell PHP to capture the value and store it as part of the $matches array so we can do something with it later.
\s+ Look for a whitespace character. Because of the +, we need it to contain at least one, but could be more than one space. I changed this from my initial code just in case there was more than one space.
(cup|tablespoon)s? This is basically an "OR" statement. It's looking for either cup or tablespoon. It can also have an s after it as in cups or tablespoons, but the ? means that it doesn't have to be there. (The s can be there, but doesn't have to be.) In this "OR" statement, you would probably want to add other things like teaspoon|pint|quart|gallon|ounce|oz|box, etc. Each item separated by a | is just another thing that it could match. The parenthesis here will capture whatever it matched and store it so we can use it later.
\s+ Same as number 2.
([-A-Z ]+) The character class [A-Z] looks for any letters. Actually any UPPERCASE letters, but you'll notice that after the expression, I use the case-insensitive i flag. This makes it so that it will match uppercase or lowercase letters. Also to this class, I have added a few other characters: the - and a space. If you run into any other characters like that that make the match fail, you can just add those characters into the class. (For instance, you may have an in apostrophe as in 1 Box Sara Lee's Cake Mix. Just add in the apostrophe into that class after the space.) The + sign means to find at least one of those characters in that class and the parenthesis capture whatever it found and saves it so that we can work with it later.
Hopefully that helps!
How about:
preg_match_all("~^([\d/ ]+?)\s+(\w+)\s+(.+)$~",
$post_meta,
$out, PREG_PATTERN_ORDER);
You can try this:
preg_match_all('/([\d\s\/]+)\s+(\w+)\s+(.*)$/',
$post_meta,
$out, PREG_PATTERN_ORDER);
$var1 = $out[1][0];
$var2 = $out[2][0];
$var3 = $out[3][0];
This is wat you need to pass as pattern :
/([\d\s/]+)\s+(\w+)\s+(.*)$

Categories