I have this string :
$str= 'To do list: - Buy milk - Feed cat';
How can I inject newlines to put the list items on their own line?
To do list:
- Buy milk
- Feed cat
I was thinking of creating a regular expression that checks if the string contains :
or -
characters and then add a <br>
tag to each of the matches ..after splitting by those parameters...
No need to explode, you can very easily convert the input text in the desired format using regex:
\s*(-\s*)
and replace with \n$1
or (<br>
instead of \n
as per your requirement)
Live demo here
Sample code in php using preg_replace
:
$re = '/\s*(-\s*)/';
$str = 'To do list: - Buy milk - Feed cat';
$subst = '\\n$1';
$result = preg_replace($re, $subst, $str);
echo $result; //To do list:\n- Buy milk\n- Feed cat