用PHP中的渐进数替换字符串(str_replace)

问题描述:

I have a php function that called in this way

breadcrumbs_func();

stamp this breadcrumbs:

<div class="breadcrumbs" itemscopeitemtype="http://schema.org/BreadcrumbList">
  <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
    <a href="#" itemprop="item"><span itemprop="name">Home</span></a>
<meta itemprop="position" content="nprog">
  </span>
  <span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
    <a href="#" itemprop="item" ><span itemprop="name">Category</span></a>
    <meta itemprop="position" content="nprog">
  </span>
</div>

When I call this function I want to replace the two content="nprog" with a progressive number (1-2-3...) in this way:

content="1", content="2"

I tried with str_replace(); but it doesn't seem to work:

$breadcrumbs =   breadcrumbs_func();
$new_breadcrumbs =   str_replace("nprog", "1", $breadcrumbs);
echo $new_breadcrumbs;

this return the breadcrumbs with no changes.

Any help?

我有一个以这种方式调用的php函数 p>

breadcrumbs_func(); code> p>

标记此痕迹: p>

 &lt; div class =“breadcrumbs”itemscopeitemtype =“http:  //schema.org/BreadcrumbList">
&lt; span itemprop =“itemListElement”itemscope itemtype =“http://schema.org/ListItem”&gt; 
&lt; a href =“#”itemprop =“item  “&gt;&lt; span itemprop =”name“&gt;主页&lt; / span&gt;&lt; / a&gt; 
&lt; meta itemprop =”position“content =”nprog“&gt; 
&lt; / span&gt; 
&lt;  span itemprop =“itemListElement”itemscope itemtype =“http://schema.org/ListItem”&gt; 
&lt; a href =“#”itemprop =“item”&gt;&lt; span itemprop =“name”&gt; Category&lt  ; / span&gt;&lt; / a&gt; 
&lt; meta itemprop =“position”content =“nprog”&gt; 
&lt; / span&gt; 
&lt; / div&gt; 
  code>  pre> \  n 
 

当我调用此函数时,我想以这种方式用渐进数字(1-2-3 ......)替换两个 content =“nprog” code>: p >

content =“1” code>, c ontent =“2” code> p>

我尝试使用 str_replace(); code>但它似乎不起作用: p> \ n

  $ breadcrumbs = breadcrumbs_func(); 
 $ new_breadcrumbs = str_replace(“nprog”,“1”,$ breadcrumbs); 
echo $ new_breadcrumbs; 
  code>  pre> 
  
 

这会返回面包屑而不做任何更改。 p>

任何帮助? p> div>

Here is a way :

function str_replace_first($search, $replace, $subject) {
    $pos = strpos($subject, $search);
    if ($pos !== false) {
        return substr_replace($subject, $replace, $pos, strlen($search));
    }
    return $subject;
}
$new_breadcrumbs =  str_replace_first("nprog", "1", $breadcrumbs);
for($i=2; $i<=substr_count($breadcrumbs,"nprog");$i++){
  echo $i;
$new_breadcrumbs =str_replace_first("nprog", $i, $new_breadcrumbs);
}
echo $new_breadcrumbs;

https://repl.it/FnSp/1

Ok I found a solution to store the echo result in the $var:

 <?php ob_start();
       breadcrumbs();
       $breadcrumbs = ob_get_contents();
       ob_end_clean();

I hope this will not affect stability or performance!