簡體   English   中英

preg_replace匹配但不替換

[英]preg_replace matching but not replacing

在下面的代碼中,我試圖獲取一些文本並圍繞它包裝一個html achor:

$d = "hello, there, how, are, you";
$d = preg_replace("/[a-zA-Z]+/", "<a href='?word=$1'>$1</a>", $d);

它正確識別每個單詞並用替換文本替換每個單詞但是它不會將匹配的單詞放入字符串中,只是將其留空。 我在使用PHP5。 我錯過了什么?

提前致謝。

你忘了抓住比賽了:

$d = "hello, there, how, are, you";
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);
//                  ^         ^ you forgot these ;-)
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);

針頭上沒有第一個子圖案。 這些都可以。 請注意第一個中的括號,它會保存捕獲組。 在第二個我們說$ 0,這意味着整場比賽。

preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);
preg_replace("/[a-zA-Z]+/", "<a href='?word=$0'>$0</a>", $d);

您錯過了括號:

$d = "hello, there, how, are, you";
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);

有一個免費的工具,有助於學習正則表達式(大多數口味,包括JS)。 下載並享受http://www.radsoftware.com.au

你忘了添加paranthesis

$d = "hello, there, how, are, you";
$d = preg_replace("/([a-zA-Z]+)/", "<a href='?word=$1'>$1</a>", $d);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM