我有像字符串"X los(2) - XYZ tres"
用於搜索大寫字母/單詞的正則表達式?
我怎麼能找到所有的大寫字母和單詞,並用隨機數字取代它們?
從第一個字符串我應該得到"2 los(2) - 6 tres"
或"9 los(2) - 5 tres"
我的意思是一個高字應該成爲一個單一的數字。
我有像字符串"X los(2) - XYZ tres"
用於搜索大寫字母/單詞的正則表達式?
我怎麼能找到所有的大寫字母和單詞,並用隨機數字取代它們?
從第一個字符串我應該得到"2 los(2) - 6 tres"
或"9 los(2) - 5 tres"
我的意思是一個高字應該成爲一個單一的數字。
這是我該怎麼做的。
使用正則表達式來查找大寫字母組,並用0
和9
(十進制系統中的所有單個數字)之間的隨機數字替換它們。
$str = preg_replace_callback('/[A-Z]+/', function() {
return rand(0, 9);
}, $str);
您可以使用preg_replace_callback查找大寫字母,並用隨機數替換它們。
$text = "X los(2) - XYZ tres";
// the callback function
function replace_with_random($matches)
{
return rand(0,9);
}
//perform the replacement
$text= preg_replace_callback(
"/[A-Z]+/",
"replace_with_random",
$text);
回調可以檢查匹配文本不是一些隨機執行更復雜的替代品 - 你會發現在$matches[0]
要兼容Unicode,使用unicode \p{Lu}
這意味着任何語言的任何大寫字母:
$str = preg_replace_callback('/\p{Lu}+/', function() {
return rand(0, 9);
}, $str);
或者一次,合法和安全地使用'e'修飾符:'preg_replace('/ [AZ] +/e',「rand(0,9)」,$ str);' – DaveRandom 2012-03-17 09:35:41
@DaveRandom是的,如果沒有捕獲組插入到代碼中,我猜'e'標記是安全的:) – alex 2012-03-17 09:37:24