たとえば、 string があり、 four のone two three four five
前後のすべての文字を削除したい場合、それが関数であることはわかっていますが、この式の書き方がわかりません。たとえば '/([az])([ AZ])/' この表現の名前と意味を教えて くださいtwo
preg_replace()
$pattern
2537 次
2 に答える
2
preg_replace ベースのソリューションを探している場合は、次のとおりです。
$str = 'one two three four five';
var_dump ( preg_replace('#^.*?(two.*?four).*$#i', '$1', $str) );
説明:最初に使用される RegEx はpreg_replace
、開始テキストまでのテキストtwo
に一致し、次に終了テキストまで一致four
し、最後に一致した文字列に置き換えて、前two
のすべてのテキストと後のすべてのテキストを破棄しますfour
。.*?
マッチングが非貪欲になることに注意してください。正規表現について詳しくは、http: //www.regular-expressions.info/をご覧ください。
出力
string(14) "two three four"
于 2012-09-20T14:12:46.990 に答える
1
preg_replace は正規表現を取り込んで置換を行う関数です。
これらは非常に強力であるため、これらについて学ぶことができますし、学ぶ必要がありますが、問題に不可欠なものではありません。
strpos
およびsubstr
機能を使用できます
substr
短縮する文字列、開始位置、および文字数を受け取り、短縮された文字列を返します。
strpos
検索する文字列と検索する文字列を取り、最初の文字列の 2 番目の文字列の場所を返します。
したがって、次のように使用できます。
$text = "one two three four five";
$locationOfTwo = strpos($text, "two"); //The location in the string of the substring "two" (in this case it's 4)
$locationOfFour =strpos($text, "four") + strlen("four"); //Added the length of the word to get to the end of it (In this case it will set the variable to 18).
$subString = subsstr($text, locationOfTwo, (locationOfFour-locationOfTwo));
于 2012-09-20T14:07:06.370 に答える