0

スマイリー記号を画像に変換し、関数内のリンクをアンカーに変換しようとしていますが、10回以上解決しようとしましたが、できませんでした。私はphpが初めてです。

ここに私のコードがあります:

 <?php
 $text = "hey :/  Theere is 2 links andc3 smiles in this text  http://google.com   then    trun nto http://yahoo.com";


function cust_text($string)
{
$content_array = explode(" ", $string);
$output = '';

foreach($content_array as $content)
{

// check word starts with http://
if(substr($content, 0, 7) == "http://")
$content = '<a href="' . $content . '">' . $content . '</a>';

//starts word with www.
if(substr($content, 0, 4) == "www.")
$content = '<a href="http://' . $content . '">' . $content . '</a>';

$output .= " " . $content;

}
output = trim($output);

$smiles = array(':/'  => 'E:\smiles\sad.jpg');
foreach($smiles as $key => $img) {

$msg =   str_replace($key, '<img src="'.$img.'" height="18" width="18" />',       $output);}

return $msg;
}

echo cust_text($text); 

?> 

その結果、スマイリーが :/ in http:// に置き換えられます 事前に感謝します :-)

4

2 に答える 2

0

これは正規表現で修正できます。

これを変える:

$msg =   str_replace($key, '<img src="'.$img.'" height="18" width="18" />',       $output);

これに:

$msg = preg_replace('~'.preg_quote($key).'(?<!http:/)~', '<img src="'.$img.'" height="18" width="18" />', $output);

しかし、初心者にとってこれは簡単な解決策ではないと言わざるを得ません。

これは、正規表現で「否定後読み」式を使用します。これは、文字列の置換とほぼ同じことを行いますが、:/ が http:/ の一部ではないかどうかを確認するために振り返るという違いがあります。2 つの ~ 文字は、正規表現の開始文字と終了文字です。~ を含むスマイリーを作成したい場合は、次のようにエスケープする必要があります: \~

これは str_replace で修正できます。

$key =   str_replace('~', '\~', $key);
于 2013-10-15T12:11:24.700 に答える
0

これを変更します: $smiles = array(':/' => 'E:\smiles\sad.jpg');

$smiles = array(' :/ ' => 'E:\smiles\sad.jpg');

スマイリーの前後のスペースに注意してください。これで、http:/ と一致しなくなりました。

于 2013-10-15T12:07:11.837 に答える