Forum Moderators: coopster
Can't seem to figure out the best way to approach this task. I have a variable ($list) which contains a series of phrases which are submitted via a textarea.
$_POST['list']="exercise bike
exercise bicycle
workout bike
workout bicycle
stairmaster
step machine
etc...";
I want to separate this big undifferentiated list into separate variables. I search $list for "bicycle" - every phrase with "bicycle" in it is removed from $list and placed into another variable (or a key in an array).
What is the best way to tackle this? Should I read $list into an array (one phrase per key), and then use some php function to tackle the job? Or should I run a regex like preg_replace($list) to do the job? Which regular expression and/or function should I use?
Thanks!
Erik
What I need to do is perform some sort of search on $list, and then take each phrase (or line \n blah blah \n) put that into its own variable/array key.
Example:
Search $list: bicycle
Extract:
excercise bicycle
workout bicycle
Those two phrases could either be in the same variable, or in seperate ones... (I can always put them togeather later). I am thinking this may be a job for regex...
I guess my question is what function do I use to search my $list variable, and move those results into a new variable?
Any ideas?
Thanks for your help!
Erik
$searchterm = 'bicycle';The pattern says to find anything between newlines (if there is a newline, this will catch the first item in the list as well) that contains our searchterm. The U means ungreedy and the i makes it case-insensitive.
$pattern = "/([^\n]*$searchterm.*)\n/Ui";
preg_match_all($pattern, $_POST['list'], $matches);
print_r($matches[1]);
For example, if I want to separate level from levels...
search: level
return: levels AND level
search: level
return: level IGNORE levels
Thanks!
Erik
$searchterm = 'level';
$pattern = "/([^\n]*$searchterm.*)\n/Uib";
preg_match_all($pattern, $_POST['list'], $matches);
print_r($matches[1]);
<b>Warning</b>: Unknown modifier 'b' in <b>PHPDocument1</b> on line <b>15</b><br />
Sorry to be so "dense" with this thing.
Thanks!
Erik
You know, I should have also dropped some links in here for you as well. There are quite a few links in Learning PHP - Books, Tutorials and Online Resources [webmasterworld.com] in the PHP Forum Library [webmasterworld.com]. They cover regular expression basics, etc.
Back to your question though -- the period (.) will match any character except newline (by default). And then you can follow the period with a modifier such as the asterisk (*), plus sign (+), etc.