I've got text where some lines are indented with 4 spaces. I've been trying to write a regex which would find every line beginning with 4 spaces and put a <span class="indented">
at the beginning and a </span>
at the end. I'm no good at regex yet, though, so it came to nothing. Is there a way to do it?
我有一些文本,其中一些行缩进4个空格。我一直在尝试编写一个正则表达式,它会找到以4个空格开头的每一行,并在开头放一个,在结尾放一个 。不过,我对正则表达式并不擅长,所以它一无所获。有办法吗?
(I'm working in PHP, in case there's an option easier than regex).
(我正在使用PHP,以防有一个比正则表达式更容易的选项)。
Example:
例:
Text text text
Indented text text text
More text text text
A bit more text text.
to:
至:
Text text text
<span class="indented">Indented text text text</span>
More text text text
A bit more text text.
3 个解决方案
#1
3
The following will match lines starting with at least 4 spaces or a tab character:
以下将匹配以至少4个空格或制表符开头的行:
$str = preg_replace("/^(?: {4,}|\t *)(.*)$/m", "<span class=\"indented\">$1</span>", $str);
#2
0
I had to do something similar, and one thing I might suggest is changing the goal formatting to be
我必须做类似的事情,我可能建议的一件事就是改变目标格式
<span class="tab"></span>Indented text text text
You can then set your css something like .tab {width:4em;}
and instead of using preg_replace and regexes, you can do
然后你可以设置你的CSS像.tab {width:4em;}而不是使用preg_replace和regexes,你可以做
str_replace($str, " ", "<span class='tab'></span>");
This has the benefit of allowing for 8 spaces to turn into a double width tab easily.
这有利于允许8个空间容易地变成双宽度标签。
#3
0
I think this should work:
我认为这应该有效:
//get each line as an item in an array
$array_of_lines = explode("\n", $your_string_of_lines);
foreach($array_of_lines as $line) {
// First four characters
$first_four = substr($line, 0, 4);
if($first_four == ' ') {
$line = trim($line);
$line = '<span class="indented">'.$line.'</span>';
}
$output[] = $line;
}
echo implode("\n",$output);
#1
3
The following will match lines starting with at least 4 spaces or a tab character:
以下将匹配以至少4个空格或制表符开头的行:
$str = preg_replace("/^(?: {4,}|\t *)(.*)$/m", "<span class=\"indented\">$1</span>", $str);
#2
0
I had to do something similar, and one thing I might suggest is changing the goal formatting to be
我必须做类似的事情,我可能建议的一件事就是改变目标格式
<span class="tab"></span>Indented text text text
You can then set your css something like .tab {width:4em;}
and instead of using preg_replace and regexes, you can do
然后你可以设置你的CSS像.tab {width:4em;}而不是使用preg_replace和regexes,你可以做
str_replace($str, " ", "<span class='tab'></span>");
This has the benefit of allowing for 8 spaces to turn into a double width tab easily.
这有利于允许8个空间容易地变成双宽度标签。
#3
0
I think this should work:
我认为这应该有效:
//get each line as an item in an array
$array_of_lines = explode("\n", $your_string_of_lines);
foreach($array_of_lines as $line) {
// First four characters
$first_four = substr($line, 0, 4);
if($first_four == ' ') {
$line = trim($line);
$line = '<span class="indented">'.$line.'</span>';
}
$output[] = $line;
}
echo implode("\n",$output);