1

可能な値が既にテキストに含まれているテキストがあります。状況に応じて適切な値を表示したいと考えています。私は正規表現が苦手で、自分の問題を説明する方法がよくわからないので、ここに例を示します。私はそれをほとんど機能させました:

$string = "This [was a|is the] test!";

preg_replace('/\[(.*)\|(.*)\]/', '$1', $string);
// results in "This was a text!"

preg_replace('/\[(.*)\|(.*)\]/', '$2', $string);
// results in "This is the test!"

これは問題なく動作しますが、パーツが 2 つある場合は、最後からエンド ブラケットを取得するため、動作しなくなります。

$string = "This [was a|is the] so this is [bullshit|filler] text";

preg_replace('/\[(.*)\|(.*)\]/', '$1', $string);
//results in "This was a|is the] test so this is [bullshit text"

preg_replace('/\[(.*)\|(.*)\]/', '$2', $string);
//results in "This filler text"

状況 1 は ( と | の間の値である必要があり、状況 2 は | と ) の間の値を示す必要があります。

4

3 に答える 3

5

あなたの問題は正規表現貪欲です。?afterを追加して.*、角かっこ内の文字列のみを消費するようにします。

 preg_replace('/\[(.*?)\|(.*?)\]/', '$1', $string);

/U同様に、 ungreedy 修飾子を使用できます。代わりに、より具体的な一致を使用することをお.*?勧めします。

于 2012-08-16T09:15:08.977 に答える
2

使用する代わりに:

(.*)

...オプショングループ内のものと一致させるには、これを使用します:

([^|\]]*)

そのパターンは | 以外のすべてに一致します。または]、繰り返し。

于 2012-08-16T09:14:16.357 に答える
1

を(「いいえ」を意味する)に置き換える際に、|文字を禁止することができます。.*.[^|]|

$string = "This [was a|is the] so this is [bullshit|filler] text";

echo preg_replace('/\[([^|]*)\|([^|]*)\]/', '$1', $string);
// results in "This was a so this is bullshit text"

echo '<br />';

echo preg_replace('/\[([^|]*)\|([^|]*)\]/', '$2', $string);
// results in "This is the so this is filler text"
于 2012-08-16T09:17:15.247 に答える