2

私はphpでのコーディングに関しては完全な初心者であり、stackoverflowへの投稿は初めてです。コードに問題があります。数字の後にスペースが続き、別の数字が続く文字列を検索し、スペースを改行できないスペースに置き換えようとしています。正規表現を使用する必要があることはわかっていますが、まだわかりません。どんな助けでも大歓迎です。私のコードは次のとおりです。

echo replaceSpace("hello world ! 1 234");
function replaceSpace( $text ){        
   $brokenspace = array(" !", " ?", " ;", " :", " …", "« ", " »", "( ", " )");
   $fixedspace = array(" !", " ?", " ;", " :", " »", " …", "« ", "( ", " )");

   return str_replace( $brokenspace , $fixedspace, $text );            
}

出力を次のようにします。

ハローワールド(nbsp)! 1(nbsp)234

4

3 に答える 3

1

これを実行する方法について、いくつかのオプションがあります。

このメソッドを引き続き使用し、呼び出しをstr_replace()組み合わせてpreg_replace()、数値とそれに続く空白と別の数値の間に非改行スペースを挿入できます。

echo _replace('hello world ! 1 234');

function _replace($text) { 
    $map = array(' !' => ' !', ' ?' => ' ?', 
                 ' ;' => ' ;', ' :' => ' :', 
                 ' …' => ' …', ' »' => ' »',
                 ' )' => ' )', '( ' => '( ', 
                 '« ' => '« '
                );
    $text = str_replace(array_keys($map), array_values($map), $text);
    return preg_replace('/(?<![^0-9]) (?=[0-9])/', '&nbsp;', $text);
}

安価なものを使用してstrtr文字を翻訳し、部分文字列を置き換えることができます。これに加えて、読みやすさと関数内で連想配列を使用できpreg_replace()ます。

echo _replace('hello world ! 1 234');

function _replace($text) { 
   $text = strtr($text, 
         array(' !' => '&nbsp;!', ' ?' => '&nbsp;?',
               ' ;' => '&nbsp;;', ' :' => '&nbsp;:', 
               ' …' => '&nbsp;…', ' »' => '&nbsp;»',
               ' )' => '&nbsp;)', '( ' => '(&nbsp;', 
               '« ' => '«&nbsp;'));

   return preg_replace('/(?<![^0-9]) (?=[0-9])/', '&nbsp;', $text);
}

単一のpreg_replace()呼び出しと結合された正規表現を使用して、上記のすべてを置き換えることができます。

$s = preg_replace('/ (?=[!?;:…»)])|(?<![^0-9]) (?=[0-9])|(?<![^«(]) /', '&nbsp;', $s);
于 2013-10-29T04:32:23.110 に答える
1

これを試すことができます:

$result = preg_replace('~(?<=[0-9]) (?=[0-9])| (?=[!?:;…»)])|(?<=[«(]) ~i', '&nbsp;', $yourString);
于 2013-10-29T04:10:39.280 に答える