PHP将字符串替换为具有reg exp的HTML实体


PHP replace string with an HTML entity with reg exp

我是使用regexp的新手,所以我想知道:如何制作一个区分大小写的正则表达式来匹配和替换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('&#38;','&#160;','&#247;'),$source);
echo $result;

结果:

&#38;,&#160;, &#247;