10

ユーザー入力をクリーンアップする関数を作成しようとしています。

完璧にしようとしているわけではありません。段落全体を大文字にするよりも、いくつかの名前と頭字語を小文字にする方がよいでしょう。

関数は正規表現を使用する必要があると思いますが、私は正規表現が苦手で、助けが必要です。

次の式の後に文字が続く場合、その文字を大文字にしたいと思います。

 "."
 ". " (followed by a space)
 "!"
 "! " (followed by a space)
 "?"
 "? " (followed by a space)

さらに良いことに、関数は「.」、「!」の後にスペースを追加できます。と "?" それらの後に文字が続く場合。

これはどのように達成できますか?

4

7 に答える 7

33
$output = preg_replace('/([.!?])\s*(\w)/e', "strtoupper('\\1 \\2')", ucfirst(strtolower($input)));

修飾子eは PHP 5.5.0 で非推奨になったため:

$output = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) {
    return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($input)));
于 2011-03-21T21:10:23.753 に答える
3

あなたが望むように行うコードは次のとおりです。

<?php

$str = "paste your code! below. codepad will run it. are you sure?ok";

//first we make everything lowercase, and 
//then make the first letter if the entire string capitalized
$str = ucfirst(strtolower($str));

//now capitalize every letter after a . ? and ! followed by space
$str = preg_replace_callback('/[.!?] .*?\w/', 
  create_function('$matches', 'return strtoupper($matches[0]);'), $str);

//print the result
echo $str . "\n";
?>

出力: Paste your code! Below. Codepad will run it. Are you sure?ok

于 2011-03-21T21:02:02.833 に答える
1

これ:

<?
$text = "abc. def! ghi? jkl.\n";
print $text;
$text = preg_replace("/([.!?]\s*\w)/e", "strtoupper('$1')", $text);
print $text;
?>

Output:
abc. def! ghi? jkl.
abc. Def! Ghi? Jkl.

.!? をエスケープする必要がないことに注意してください。中身 []。

于 2011-03-21T21:08:21.530 に答える
1

これはどう?正規表現なし。

$letters = array(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
);
foreach ($letters as $letter) {
    $string = str_replace('. ' . $letter, '. ' . ucwords($letter), $string);
    $string = str_replace('? ' . $letter, '? ' . ucwords($letter), $string);
    $string = str_replace('! ' . $letter, '! ' . ucwords($letter), $string);
}

私にとってはうまくいきました。

于 2016-08-25T18:02:28.250 に答える
1

区切り文字として使用して、文字列を配列に区切ります./!/?。各文字列をループして を使用しucfirst(strtolower($currentString))、再度結合して 1 つの文字列にします。

于 2011-03-21T20:57:51.730 に答える
-2
$Tasks=["monday"=>"maths","tuesday"=>"physics","wednesday"=>"chemistry"];

foreach($Tasks as $task=>$subject){

     echo "<b>".ucwords($task)."</b> : ".ucwords($subject)."<br/>";
}
于 2018-12-17T16:00:38.050 に答える