我想要一种方法来改变字符串的一部分,根据简单的标记。例如:
$string = "I'm student (at JIC college), and I'm GENIUS.";
我想选择at JIC college
或括号之间的任何单词并更改其颜色。(我知道如何改变它们的颜色)。但是如何选择它,改变它,然后把它放回去。以及即使我有超过1个括号,如何做到这一点
$string = "I'm student (at JIC college), and I'm GENIUS (not really).";
您可以使用preg_replace
来实现这一点。
$string = "I'm student (at JIC college), and I'm GENIUS (not really).";
$string = preg_replace('/'(([^')]+)')/', '<span style="color:#f00;">$1</span>', $string);
不幸的是,这个例子有点不清楚,因为您选择的封装在正则表达式中丢失了,需要转义。如果你想让你的代码更清晰,我会使用括号以外的东西!
可以使用explosion ():
$string = "I'm student (at JIC college), and I'm GENIUS (not really).";
$pieces = explode("(", $string );
$result = explode(")", $pieces[1]);
echo $result[0]; // at JIC college
通过此函数获取字符串between ()
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "this is my [tag]dog[/tag]";
$parsed = get_string_between($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)
您可以使用正则表达式实现这一点:
$colorized = preg_replace('/('(.*?'))/m', '<span style="color:#f90;">($1)</span>', $string);