2015-07-20 30 views
0

我允許用戶將文本輸入到textarea中,但編寫*https://example.com/image.png*(用星號包圍的URL)需要採用URL(它應該始終是URL),然後將其插入到<img />標記中然後用圖像標記替換URL和星號。如何用另外的東西替換兩個星號之間的文本?

我能夠趕上事件一次,但我不確定如何找到這個多次。在一個實例中,將代替原來的:

*https://example.com/image.png* 

與:

<img src="https://example.com/image.png" /> 

編輯:

作爲一個簡單的例子:

輸入:

A load of random text *http://example.com/image.png* some more text. Some more text *http://example.com/image2.jpg* the end. 

它需要能夠找到兩個星號中的每一個,並獲得裏面的內容。

例如:

http://example.com/image.png 
http://example.com/image2.jpg 

所以,我可以再使用的URL來顯示圖像。

然後用像這樣結束:

A load of random text <img src="http://example.com/image.png" /> some more text. Some more text <img src="http://example.com/image2.jpg" /> the end. 
+2

問題是關於? – donald123

+0

@ donald123最好的方法去做這件事 –

+0

這是什麼?目前還不清楚你想在這裏做什麼。 – Daan

回答

6

這是可以做到使用正則表達式:

$string = 'A load of random text *http://example.com/image.png* some more text. Some more text *http://example.com/image2.jpg* the end.'; 
$pattern = '/\*(.*?)\*/'; 
$replacement = '<img src="$1" />'; 
echo preg_replace($pattern, $replacement, $string); 

關於模式,\*匹配文字*(.*?)捕獲任何東西(但由儘可能少的人物)兩顆星之間。

查看正則表達式here。閱讀有關preg_replacehere的PHP文檔。

如果接受用戶輸入,您應該考慮XSS問題。

相關問題