简体   繁体   English

如果PHP中的前几个匹配x,如何检查前几个字符,在前几个之后添加字符?

[英]How Can I Check First Few Characters, Add Characters After First Few if First Few Match x in PHP?

I want to perform a three step process: 我要执行一个三步过程:

  1. Check the first few characters (ffc) of a string variable. 检查字符串变量的前几个字符(ffc)。
  2. If ffc = x (another string of characters) Then 如果ffc = x (另一个字符串),则
  3. Insert x after ffc but before any other content in ffc . ffc之后但在ffc任何其他内容之前插入x

How can I accomplish this in PHP? 如何在PHP中完成此操作?

Actual Use Case: 实际用例:

I am using WordPress and grabbing the_content() and moving it into a variable $content . 我正在使用WordPress并抓取the_content()并将其移动到变量$content

I want some characters to appear before the text in $content, but WP auto adds <p> tags (if wpautop is on, and I'd like to avoid turning it off), which means the characters I add appear above rather than on the same line as $content . 我希望某些字符出现在$ content中的文本之前,但是WP auto会添加<p>标记(如果wpautop已启用,并且我希望避免将其关闭),这意味着我添加的字符显示在上方而不是在与$content相同。

The goal here is to check if $content starts with <p> and if it does to insert after <p> the characters "Summary: ". 此处的目标是检查$content是否以<p>开头,以及是否确实在<p>之后插入字符“摘要:”。

Here is what I have thus far (it isn't working): 到目前为止,这是我所拥有的(它不起作用):

<?php
 $content = get_the_content();
 echo $content;
 $hasP = substr($content, 0, 3);
 echo $hasP; 
 If ($hasP == '<p>') {
   echo "Yes!";
   $newString = substr($string, 3);
   echo $newString;
 };
 ?>

Unfortunately, it seems that WP just re-adds the <p> when I echo $newString. 不幸的是,当我回显$ newString时,WP似乎只是重新添加了<p>

So, this took a long time for me to figure out, but here is the solution I came up with (err, make that stole from other people): 因此,我花了很长时间才弄清楚,但这是我想出的解决方案(错误,被其他人偷走了):

<?php
add_filter('the_content', 'before_after');
$content = the_content();
echo $content;
?>

And then the actual magic happens here: 然后真正的魔术发生在这里:

function before_after($content) {
    $content = preg_replace('/<p>/', '<span>', $content, 1);
    $content = preg_replace('/<\/p>/', '</span>', $content, 1);
    return $content;
}

In the above I actually went beyond what I had initially stated and replaced both the opening and closing <p> . 在上面,我实际上超出了我最初所说的内容,并替换了<p>开头和结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM