Home > Backend Development > PHP Tutorial > preg_replace有关问题求解

preg_replace有关问题求解

WBOY
Release: 2016-06-13 13:13:56
Original
1044 people have browsed it

preg_replace问题求解
我又一个字符串:
$html = '

  • 《mainGood》
  • 《subGood》《subGood》
';//《mainGood》《subGood》个数不定

我现在用echo preg_replace("/(《mainGood》)|(《subGood》)/is",回调函数,$html);

我本来想用回调函数的方法替换《mainGood》为1,第一个《subGood》为2,第三个《subGood》为3,依次类推,我本来想在回调函数中获取到当前替换的是第几个,然后确定替换内容。但是在回调函数中不知道该怎么写了,请高手帮下忙。

------解决方案--------------------
是这个意思么?
PHP code
<?php $html = '<ul>
Copy after login
  • 《mainGood》《mainGood》
  • 《subGood》《subGood》《subGood》
  • '; echo preg_replace("/(《mainGood》|《subGood》)/eis","foo('$1')",$html); function foo($v){ global $count; if($v=='《mainGood》'){ return 1; }else{ $count++; return $count+1; } } //
    • 11
    • 234

    ------解决方案--------------------
    $num_mainGood = $num_subGood = 0;
    echo preg_replace_callback("/(《mainGood》)|(《subGood》)/is", '回调函数', $html);

    function 回调函数($r) {
    global $num_mainGood, $num_subGood;
    if($r[1]) $num_mainGood++;
    if($r[2]) $num_subGood++;
    //以下写返回内容的代码

    }

    ------解决方案--------------------
    PHP code
    [liangdong@bb-browser-test00.vm.baidu.com php_project]$ php main.php 
    
    Copy after login
    • a
    • bc
    [liangdong@bb-browser-test00.vm.baidu.com php_project]$ cat main.php
  • 《mainGood》
  • 《subGood》《subGood》
  • EOF; $count = 0; $map = array(0 => 'a', 1 => 'b', 2 => 'c'); $result = preg_replace_callback('/《mainGood》|《subGood》/i', function($match) { global $count; global $map; return $map[$count++]; }, $html); echo $result . PHP_EOL; ?>
    Related labels:
    gt li lt
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template