PHP 使用正则表达式将字符串替换为 HTML 实体
PHP replace string with an HTML entity with reg exp
我是正则表达式的新手,所以我想知道:如何制作区分大小写的正则表达式来匹配和替换 php 中的以下内容:
#ampersand# => &
#space# =>  
#through# => ÷
其他一切如:
# ampersand#, #ampersand #, # ampersand #
# space#, #space #, # space #
# through#, #through #, # through #
应该被忽略。
感谢任何帮助!
这样的函数怎么样?
function convertToEntity($string) {
$search = array("#ampersand#", "#space#", "#through#");
$replace = array("&", " ", "÷");
$newstring = str_replace($search, $replace, $string);
return $newstring;
}
<?php
$source = '#ampersand #,# space#, # through #';
$result = preg_replace(array('/#\s*ampersand\s*#/i','/#\s*space\s*#/i','/#\s*through\s*#/i'),array('&',' ','÷'),$source);
echo $result;
结果:
&, , ÷
我是正则表达式的新手,所以我想知道:如何制作区分大小写的正则表达式来匹配和替换 php 中的以下内容:
#ampersand# => &
#space# =>  
#through# => ÷
其他一切如:
# ampersand#, #ampersand #, # ampersand #
# space#, #space #, # space #
# through#, #through #, # through #
应该被忽略。
感谢任何帮助!
这样的函数怎么样?
function convertToEntity($string) {
$search = array("#ampersand#", "#space#", "#through#");
$replace = array("&", " ", "÷");
$newstring = str_replace($search, $replace, $string);
return $newstring;
}
<?php
$source = '#ampersand #,# space#, # through #';
$result = preg_replace(array('/#\s*ampersand\s*#/i','/#\s*space\s*#/i','/#\s*through\s*#/i'),array('&',' ','÷'),$source);
echo $result;
结果:
&, , ÷