我要做的是,如果存在,请删除“短代码”中出现的文本,例如:Here's some content [shortcode]I want this text removed[/shortcode] Some more content
要更改为Here's some content [shortcode][/shortcode] Some more content
.
这似乎是一件很简单的事情,但我无法弄清楚.. =/
短代码只会在整个字符串中出现一次。
提前感谢您的帮助。
试试这个:
$var = "Here's some content [shortcode]I want this text removed[/shortcode] Some more content";
$startTag = "[shortcode]";
$endTag = "[/shortcode]";
$pos1 = strpos($var, $startTag) + strlen($startTag);
$pos2 = strpos($var, $endTag);
$result = substr_replace($var, '', $pos1, $pos2-$pos1);
使用 preg_replace() 很容易做到。出于您的目的,/\[shortcode\].*\[\/shortcode\]/
用作模式。
$replace = "[shortcode][/shortcode]";
$filteredText = preg_replace("/\[shortcode\].*\[\/shortcode\]/", $replace, $yourContent);
有关详细信息,请参阅http://php.net/manual/en/function.preg-replace.php 。
可以使用 strpos() 查找字符串中 [substring] 和 [/substring] 的位置,并通过 substr_replace() 将文本替换为空格
如果您不想打扰常规的表达:
如果[shortcode]
字符串中确实有标签,那真的没问题:只需使用 substr 的嵌套使用:
substr($string,0,strpos($string,'[substring]')+11)+substr($string,strpos($string,'[/substring]'),strlen($string))
其中第一个 substr 将字符串剪切到要剪切的字符串的开头,第二个添加字符串的剩余内容。
看这里:
在 php 中使用正则表达式来摆脱它。
preg_replace (shortcode, urText, '', 1)
$string = "[shortcode]I want this text removed[/shortcode]";
$regex = "#\[shortcode\].*\[\/shortcode\]#i";
$replace = "[shortcode][/shortcode]";
$newString = preg_replace ($regex, $replace, $string, -1 );
$content = "Here's some content [shortcode]I want this text removed[/shortcode] Some more content to be changed to Here's some content [shortcode][/shortcode] Some more content";
print preg_replace('@(\[shortcode\])(.*?)(\[/shortcode\])@', "$1$3", $content);
产量:
这是一些内容 [shortcode][/shortcode] 还有一些内容要改成 这里是一些内容 [shortcode][/shortcode] 还有一些内容