繁体   English   中英

PhP 在两个不同的字符串之间查找(并替换)字符串

[英]PhP Find (and replace) string between two different strings

我有一个字符串,看起来像这样"<html>" 现在我想要做的是获取"<"">"之间的所有文本,这应该适用于任何文本,这样如果我做了"<hello>""<p>"也将工作。 然后我想用包含标签之间的字符串的字符串替换这个字符串。 例如
在:

<[STRING]>

出:

<this is [STRING]>

其中 [STRING] 是标签之间的字符串。

使用捕获组匹配<之后不是> ,并将其替换为替换字符串。

preg_replace('/<([^>]*)>/, '<this is $1>/, $string);

这是一个测试模式存在的解决方案,然后捕获它以最终修改它......

<?php
$str = '<[STRING]>';
$pattern = '#<(\[.*\])>#';

if(preg_match($pattern, $str, $matches)):
    var_dump($matches);
    $str = preg_replace($pattern, '<this is '.$matches[1].'>', $str);
endif;

echo $str;
?>

回声 $str; 你可以在这里测试: http : //ideone.com/uVqV0u

我不知道这对你是否有用。 您可以使用正则表达式,这是最好的方法 但是您也可以考虑使用一个小函数从字符串中删除第一个<和最后一个>字符。

这是我的解决方案:

<?php

/*Vars to test*/

$var1="<HTML>";
$var2="<P>";
$var3="<ALL YOU WANT>";

/*function*/

function replace($string_tag) {
$newString="";
for ($i=1; $i<(strlen($string_tag)-1); $i++){
    $newString.=$string_tag[$i];
}

return $newString;

}

/*Output*/

echo (replace($var1));
echo "\r\n";
echo (replace($var2));
echo "\r\n";
echo (replace($var3));

?>

输出给我:
HTML

随心所欲

https://ideone.com/2RnbnY 上测试

暂无
暂无

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

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