简体   繁体   English

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

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

I have a string, that look like this "<html>" .我有一个字符串,看起来像这样"<html>" Now what I want to do, is get all text between the "<" and the ">" , and this should apply to any text, so that if i did "<hello>" , or "<p>" that would also work.现在我想要做的是获取"<"">"之间的所有文本,这应该适用于任何文本,这样如果我做了"<hello>""<p>"也将工作。 Then I want to replace this string with a string that contains the string between the tags.然后我想用包含标签之间的字符串的字符串替换这个字符串。 For example例如
In:在:

<[STRING]>

Out:出:

<this is [STRING]>

Where [STRING] is the string between the tags.其中 [STRING] 是标签之间的字符串。

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

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

here is a solution to test on the pattern exists and then capture it to finally modify it ...这是一个测试模式存在的解决方案,然后捕获它以最终修改它......

<?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;
?>

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

I don't know if this can be usefull to you.我不知道这对你是否有用。 You can use a regular expression that is the best way .您可以使用正则表达式,这是最好的方法 But you can also consider a little function that remove first < and last > char from your string.但是您也可以考虑使用一个小函数从字符串中删除第一个<和最后一个>字符。

This is my solution:这是我的解决方案:

<?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));

?>

Output give me:输出给我:
HTML HTML
P
ALL YOU WANT随心所欲

Tested on https://ideone.com/2RnbnYhttps://ideone.com/2RnbnY 上测试

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

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