replace space with new line

主宰稳场 提交于 2019-11-27 19:33:29

问题


I have a string thats separated by a space. I want to show every part of the string on new line that is separated by space. how can I do that.

base1|123|wen dsj|test base2|sa|7243|sdg  custom3|dskkjds|823|kd    

if there is no more | after an initial pipe then the space should break the line and it should look like this

base1|123|wen dsj|test 
base2|sa|7243|sdg  
custom3|dskkjds|823|kd  

回答1:


This is pretty messy, yet to clean up the last empty result:

$string = 'base1|123|wen dsj|test base2|sa|7243|sdg custom3|dskkjds|823|kd';
preg_match_all('/(?P<line>(?:[^\\| ]*\\|{0,1})*(?: [^\\| ]*\\|[^\\| ]*(?: |\\z){0,1})*)(?: |\\z)/',$string,$matches,PREG_SET_ORDER);
print_r($matches);

Edit: Actually this is pretty horrible




回答2:


echo str_replace(' ',"\n",$string);

or

echo str_replace(' ',PHP_EOL,$string);


来源:https://stackoverflow.com/questions/4102510/replace-space-with-new-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!