次のような文字列があります。
text..moretext,moartxt..,asd,,gerr..,gf,erg;ds
これは基本的に、可変量のテキスト、可変量の句読点、さらに可変量のテキストなどです。
正規表現を使用してPHPで上記の文字列をこれに変換するにはどうすればよいですか?
text. .moretext, moartxt. . ,asd, ,gerr. . ,gf, erg; ds
各単語の両側に句読点を 1 文字だけ含めることができます。
これを 2 つのパスで行います。まず、各単語の後の句読点です。次に、単語の前の句読点のパス。
<?php
$sourcestring="text..moretext,moartxt..,asd,,gerr..,gf,erg;ds";
echo preg_replace('/(\w[.,;])([^\s])/i','\1 \2',$sourcestring);
?>
$sourcestring after replacement:
text. .moretext, moartxt. .,asd, ,gerr. .,gf, erg; ds
<?php
$sourcestring="text. .moretext, moartxt. .,asd, ,gerr. .,gf, erg; ds";
echo preg_replace('/([^\s])([.,;]\w)/i','\1 \2',$sourcestring);
?>
$sourcestring after replacement:
text. .moretext, moartxt. . ,asd, ,gerr. . ,gf, erg; ds
これをpreg_replace_callbackで解決しましょう:
Code
$string = 'text..moretext,moartxt..,asd,,gerr..,gf,erg;ds';
$chars = '\.,;'; // You need to escape some characters
$new_string = preg_replace_callback('#['.$chars.']+#i', function($m){
return strlen($m[0]) == 1 ? $m[0].' ':implode(' ', str_split($m[0]));
}, $string); // This requires PHP 5.3+
echo $new_string; // text. .moretext, moartxt. . ,asd, ,gerr. . ,gf, erg; ds