查找并替换字符串

时间:2016-12-07 04:39:51

标签: php

嗨伙计请帮我解决这个问题。

$string='1. New ‘benami’ Act to take effect from Nov. [Governance]
1. The Benami Transactions (Prohibition) Amendment Act will come into force 2. New ‘benami’ Act to take effect from Nov. [Governance]
2. The Benami Transactions (Prohibition) Amendment Act will come into force';

for($i=1;$i<=8;$i++)
{
    $string = str_replace($i.'.', "<li>", $string);
}
echo  $string;

上面的代码用li替换所有1.但是我需要先用h3替换1.然后用li替换第二个1.等等

3 个答案:

答案 0 :(得分:0)

由于你过多地简化了问题中的例子,所以你真正想要的并不是很清楚。

但根据你给出的内容,尝试这样的事情:

$stringArray = split('1. ', $string);
$h3 = array_shift($string);
$h3 = "<h3>".$h3."</h3>";
foreach ($stringArray as $key => &$string) {
    $stringarray[$key] = "<li>".$string."</li>";
}

答案 1 :(得分:0)

你可以做到的一种方法是将它分解成一系列物品,然后将它们与包裹在相应标签中的碎片放在一起

$array = preg_split('/\d+\. / ', $string);
echo '<h3>' . $array[1] . '</h3><li>' . implode('</li><li>', array_slice($array, 2)) . '</li>';

答案 2 :(得分:0)

   $string='1. New ‘benami’ Act to take effect from Nov. [Governance] 1. The Benami Transactions (Prohibition) Amendment Act will come into force   ........';
   $string=trim($string);             
   $Arr=explode("1.",$string);
   array_filter($Arr);
   $string="<h3>".$Arr[1]."</h3><li>".$Arr[2]."</li>";
   echo $string;


 Below link for output

  [1]: https://i.stack.imgur.com/w6qZp.png