2012-11-24 19 views
2

好了,所以我有一个网站,用户可以编写并提交内容上常见的HTML表单。如何使用PHP来改变输入的文本

我想要写一个PHP一块那获得了整个文本,并将其转换某些特定的值。

例如,文本:

Etiam非普鲁斯在悲placerat sollicitudin。在dignissim elit utiteroitso sodales a sodales nunc blandit。 Suspendi sse vitae odio mauris,eu pulvinar augue。在坐在自由之前vel tellus posuere volutpat。 twitter :: Lipsum facebook :: Lipsum Nulla sed purus vel orci ultrices tincidunt。 Maecenas non sem eget risus volutpat placerat。

通知之实 :: Lipsum 叽叽喳喳:: Lipsum

我想PHP来浏览文本和知道的Facebook :: Lipsum应自动更改为http://www.facebook.com/Lipsum和Twitter的一个http://www.twitter.com/Lipsum

任何人都可以就如何做到这一点(有或的preg_match str_replace函数)建议?我不确定是否搜索了一段时间,但没有发现任何具体内容。

非常感谢

+0

如果你想在客户端,这将不得不你se javascript。 –

+0

使用我的代码JavaScript的instad,因为Js可以在一些浏览器中,出于安全或其他原因 – samayo

回答

1

你可以取代一般含有::标记,像这样的任何文本:

$text = "Etiam non purus in dolor placerat sollicitudin. In dignissim elit ut libero sodales a sodales nunc blandit. Suspendi sse vitae odio mauris, eu pulvinar augue. In sit amet libero vel tellus posuere volutpat. twitter::Lipsum facebook::Lipsum Nulla sed purus vel orci ultrices tincidunt. Maecenas non sem eget risus volutpat placerat."; 

preg_replace("[(\w+)::]", "http://www.$1.com/", $text); 

它说抓住任何文本块包含::与http://www.{string}.com/

[(\w+)::]手段取代匹配任何单词字符并结束于:: - 大括号表示包含此内容的整体,因此仅[::]只会替换:: while [(\ w +)以任何单词开头,直到它遇到::]并将该值赋给()t o该变量$ 1

http://msdn.microsoft.com/en-us/library/az24scfc.aspx

+0

转过来,这似乎比我的答案更好。但[(\ w +)::]是什么意思? – samayo

+0

我更新了解释 –

+0

谢谢你的帮助,这很奇妙 – djjavo

-1

您也可以使用preg_*功能:

$arr = array(
    'twitter' => 'www.twitter.com', 
    'facebook' => 'www.facebook.com' 
    // use lowercase keys here 
    // or uncomment the next line 
); 
//$arr = array_change_key_case($arr,CASE_LOWER); 

function replaceLinks($m) { 
    global $arr; 
    // make this array accessible 
    $key = $m[1]; // this is the array key 
    $page = $m[2]; // this is the part after :: 
    $addr = 'http://'.$arr[strtolower($key)].'/'.$page; 
    // get the value (address) from the array 
    return "<a href=\"$addr\" target=\"_blank\">$addr</a>"; 
    // and return it as an anchor element 
} 

$newStr = preg_replace_callback(
    '~\b('.implode('|',array_keys($arr)).')::(\S*)~i', 
    // this will basically compile into the following pattern: 
    // ~\b(twitter|facebook)::(\S+)~i 
    // where \b signifies beginning of word 
    // and \S* signifies 0 or more non empty chars 
    // so don't forget to urlencode or rawurlencode 
    // the part after :: just in case 
    'replaceLinks', // execute this function 
    $str 
); 

echo "<p>$newStr</p>"; 
0

请注意,这只是比赛的Twitter和Facebook

preg_replace("/(facebook|twitter)::([\w]+)/", '<a href="http://www.$1.com/$2" target="_blank">http://www.$1.com/$2</a>', $yourText); 

演示:http://codepad.viper-7.com/hs3xgw

+0

也很简单有效地解释,谢谢 – djjavo

相关问题