【问题标题】:Post content manipulation with substr_replace使用 substr_replace 发布内容操作
【发布时间】:2017-11-20 21:33:57
【问题描述】:

EB 晚安! 我是一个 php 新手,被一些简单的任务困住了。

我想在帖子内容的第 5 个句号之后插入一个字符串。但是,我仍然坚持编写替换的第一步。之后,我会将计数添加到 $pos。 我也尝试过 substr_replace()。

这是我在我的主题的 function.php 文件中的代码。

function replace_content($content)
{
    $oldstr = $content;
    $str_to_insert = "tst";
    $pos = 30;
    $new_content = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);


    return $new_content;
}
add_filter('the_content','replace_content');

它没有返回预期的结果。 感谢您的建议和帮助。

【问题讨论】:

    标签: php wordpress post replace


    【解决方案1】:

    你可以只使用explode 函数在'.' 的第五次出现之后添加字符串。例如,您可以使用以下函数:

    function replace_content($content)
    {
        $str_to_insert = "tst";
        $pos = 5;
    
        $data = explode(".", $content);
        $data[5] = $str_to_insert . " " . $data[5];
        $new_content = implode(".", $data);
    
        return $new_content;
    }
    

    【讨论】:

      【解决方案2】:

      我不确定,是否存在任何内置方法。但是,您的问题有解决方法

      您可以使用explode 并一起循环

      $array = array(".",$content); //split by fullstop and store it in array
      $new_content = ""
      $str_to_insert = "tst";
      $count=1
      
      foreach($array as $value) { // loop through the array now
        if($count==5)
         {
         $new_content = $new_content.$value.$str_to_insert."."; // insert string on fifth occurrence 
         }
        else
        {
        $new_content = $new_content.$value."."; // otherwise just append string as it was
        }
       $count++;
      }
      

      【讨论】:

      • 我想你错过了圣。 $new_content 没有定义!?我测试了它。它将 string_to_insert 放在 content.if($count==1) 或 if($count==2) 之前或之后,同时 content 超过 2。
      • 是的,10 倍。这是个好主意,但实际上并没有奏效。为什么你有 $new_content = "" 空白?不应该是里面的数组吗?
      • 那是什么都没有初始化。不工作是什么意思。您能使用我的代码分享输出和预期输出吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 2011-12-06
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多