如何在PHP中的任何标点符号和标记之间添加空格?

时间:2014-11-17 10:38:25

标签: php regex string

我想在每个标点符号和标记之间添加一个空格,以便文本看起来像这样:

 " in dreams " might keep you awake at night , but not because of its creepy imagery , bizarre visual style or story about a clairvoyant madman who lures young girls to their untimely deaths . 
no , the source of potential sleeplessness here lies within the movie's brutally squandered potential , the least of which is an admittedly nifty premise - even by tired serial killer genre standards . 
the big letdown , however , comes upon the realization that this 100-minute head-scratcher was masterminded by neil jordan , the man behind " the crying game . " 
he's no stranger to cinematic weirdness , but this nutty nonsense really pushes the envelope . 
things start out strong enough , with cinematographer darius khondji's stunning camera work guiding viewers into the bowels of a underwater ghost town during a creepy prologue that establishes a notably grim tone right off the bat . 
this eerie opulence remains a dazzling display of showmanship throughout the entire film - there's even something macabre about the way khondji photographs a rustic , seemingly innocent new england autumn - but if there ever was a film that didn't deserve so good a polish , it's this one .

请注意,输入字符串可以是,例如,“这是一个简单的 - 直截了当的P.H.P.程序!不是吗?”

输出应该是:“这是一个简单的 - 直接的P.H.P。程序!不是吗?”

在这种情况下,标点字符是任何不是字母或数字的字符。

1 个答案:

答案 0 :(得分:0)

我建议不要在你的情况下使用“饥饿”的正则表达式引擎,简单的字符串替换就可以完成这项工作:

<?php
$input_string = "bla bla,bla.another bla;";
//you can extend this array as you wish
$punctoations = array(".",",",":",";");  
//your replacements, same order as above array    
$replacements = array (" . "," , "," : "," ; "); 
echo str_replace($punctoations, $replacements, $input_string);
?>

了解PHP documentation中的更多信息。