0

私はひもを持っています。PHP (および最も簡単なソリューション、おそらく preg_replace) を使用して、次のことを行います。

  1. 文字列から最後の 5 文字 (単語ではない) を見つけます。

  2. これらの最後の 5 文字の 1 つに「&」文字が含まれている場合、この & 文字とそれに続くその他の文字を削除したいと考えています。

たとえば、文字列が次の場合:

$string='Hello world this day and tomorrow';

スクリプトは次を見つける必要があります:

' orrow';

(「orrow」には「&」が含まれていないため、何もしません)。

でもいつ:

$string='Hello world this day and tomor &row';また

$string='Hello world this day and tomo &rrow';また

$string='Hello world this day and tomorrow &';また

$string='Hello world this day and tomorrow&q';また

$string='Hello world this day and tomorrow &co';

スクリプトは、& の後のすべての文字 (& を含む) を削除する必要があります。

4

3 に答える 3

2

正規表現:&.{0,4}$トリックを行う必要があります。& 文字の後 (および含む) の末尾の前の最後の 0 ~ 4 文字を検索します。

$string = 'Hello World&foo';
echo $string;
$string = preg_replace('/&.{0,4}$/', '', $string);
echo $string;
于 2013-09-17T22:49:07.910 に答える
0

これはうまくいくはずです:

for($i=max(0, strlen($string)-5);$i<strlen($string);$i++) {
    if($string[$i] == '&') {
        $string = substr($string,0,$i);
        break;
    }
}
于 2013-09-17T22:43:41.323 に答える