PHP使用reg exp

时间:2016-04-30 23:23:21

标签: php html regex preg-replace

我是使用regexp的新手,所以我想知道:我如何制作一个区分大小写的正则表达式来匹配并替换php中的以下内容:

#ampersand# => &
#space# =>  
#through# => ÷

其他一切如下:

# ampersand#, #ampersand #, # ampersand #
# space#, #space #, # space #
# through#, #through #, # through #

应该被忽略。

感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

这样的功能怎么样?

function convertToEntity($string) {
  $search = array("#ampersand#", "#space#", "#through#");
  $replace = array("&", " ", "÷");
  $newstring = str_replace($search, $replace, $string);
  return $newstring;
}

答案 1 :(得分:0)

<?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;