1

I want a way to change part of string according to simple marks. for example:

$string = "I'm student (at JIC college), and I'm GENIUS.";

I want to select at JIC college or any words between brackets and change their color. (I know how to change their color). but how to select it change it then put it back. and how to do that even if I had more than 1 brackets.

$string = "I'm student (at JIC college), and I'm GENIUS (not really).";
4

4 回答 4

2

您可以使用 apreg_replace来实现这一点。

$string = "I'm student (at JIC college), and I'm GENIUS (not really).";

$string = preg_replace('/\(([^\)]+)\)/', '<span style="color:#f00;">$1</span>', $string);

不幸的是,这个例子有点不清楚,因为您选择的封装在正则表达式中丢失并且需要转义。如果你想让你的代码清晰,我会使用括号以外的东西!

于 2013-04-18T06:27:41.967 回答
0

您可以使用explode()

$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
于 2013-04-18T06:23:48.417 回答
0

通过该函数获取()之间的字符串

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)

并改变颜色。

于 2013-04-18T06:27:54.017 回答
-1

您可以使用正则表达式来实现:

$colorized = preg_replace('/(\(.*?\))/m', '<span style="color:#f90;">($1)</span>', $string);
于 2013-04-18T06:25:46.453 回答