-3

テキスト内の最後のスペースを見つける正規表現を探していますが、HTML タグ内のスペースを見つけたくありません。

"This is a string with <strong>some</strong> html in it"

正規表現が見つけるべきスペースは、 と の間のスペースinですit。その正規表現はそれほど難しくありません。ここでも同じ正規表現が機能します。

"This is a string with <strong>some</strong> html in <a href="">the end</a>"

スペースは HTML の と の間にtheなりますend(OK!)

しかし、私の文字列が次の場合:

"This is a string with <strong>some</strong> html in the <a href="">end</a>"

次に、スペースは と の間the<aはなくと の間にある必要が<aありhref="">end<a>ます。

誰かアイデアはありますか?

4

1 に答える 1

3

要件に関する詳細情報が明らかになったため、この回答を更新します。

strip_tags()strrpos()substr()関数の組み合わせがうまくいきます。最初に HTML を消去するには、strip_tags() 関数を使用します。その後、テキストが残り、それを展開して最後の単語を見つけ、 strrpos() を使用して元のテキスト内のその単語の位置を見つけることができます。

$stringToken = explode( ' ', strip_tags( $str ) );
// Find the second-to-last word in the string.
$word = $stringToken[ count( $string ) - 2 ];

// Use $word to find its position within the original HTML-encoded string.
$wordPosition = strrpos( $str, $word );

if( $wordPosition !== false )
{
    $finalSpace = strpos( $str, ' ', $wordPosition );
    $lastSpacePrefix = substr( $str, 0, $finalSpace );
    $lastSpaceSuffix = substr( $str, $finalSpace + 1 );
    $newStr = sprintf( "%s%s%s", $lastSpacePrefix, $finalSpaceSub, $lastSpaceSuffix );
}
于 2012-08-23T13:58:17.560 に答える