Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php preg_替换为以*开头的文本。并以\r或\n结尾_Php_Regex - Fatal编程技术网

php preg_替换为以*开头的文本。并以\r或\n结尾

php preg_替换为以*开头的文本。并以\r或\n结尾,php,regex,Php,Regex,我在php中有2个文本字符串,我想将它们更改为html标记 第一: *.some text * some text 第二: #.sometext # sometext 我想将以“*”或“*”开头并以“\r”或“\n”结尾的第一个字符串改为 我想将以“.”或“”开头并以“\r”或“\n”结尾的第二个字符串改为 我编写了这个正则表达式代码,但不起作用: $regex1 = "#([*.])(.*)([\n])#e"; $text = preg_replace($regex1,"('<li&

我在php中有2个文本字符串,我想将它们更改为html标记

第一:

*.some text
* some text
第二:

#.sometext
# sometext
我想将以“*”或“*”开头并以“\r”或“\n”结尾的第一个字符串改为

我想将以“.”或“”开头并以“\r”或“\n”结尾的第二个字符串改为

我编写了这个正则表达式代码,但不起作用:

$regex1 = "#([*.])(.*)([\n])#e";
$text = preg_replace($regex1,"('<li>$2</li>')",$text);

$regex2 = "#([#.])(.*)([\n])#e";
$text = preg_replace($regex2,"('<ol>$2</ol>')",$text);
我该怎么办


非常感谢

我建议对您的代码进行一些更改,我将在下面解释

首先是守则:

<?php
$text = "
first :

*.some text
* some text

and second :

#.sometext
# sometext
";

$regex1 = "#\*(.| )(.*?)\n#";
$text = preg_replace($regex1,"<li>$2</li>\n",$text);

$regex2 = "#\#(.| )(.*?)\n#";
$text = preg_replace($regex2,"<ol>$2</ol>\n",$text);

echo $text;
以及输出

first :

<li>some text</li>
<li>some text</li>

and second :

<ol>sometext</ol>
<ol>sometext</ol>
变化:

您不需要在正则表达式中使用e修饰符 为了匹配*。和*,只需指定*转义到\*,以及的OR条件。逃到\。和 使用。*的非贪婪版本,即…*?所以你只吃尽可能少的文字。 PS:这可能不是你想要的,ol有这样的结构:……但我根据你的问题规范编写了代码。你应该能够修改它

$str=<<<STR
abc
*.some text
* some text
def
STR;

echo preg_replace('/[\r\n]+<\/li>/i',"</li>",preg_replace('/\*[\.\s](.*)$/im',"<li>$1</li>",$str));

为了避免这种情况,我添加了另一个正则表达式来修复[newline]。

多亏了我的朋友的评论。但是我写了很多标记,只有这些标记是不完整的。如果我写了这两个,它就完成了。@Vyktor,他没有解析html。他正在解析Markdown之类的东西,正则表达式对它的解析要比html好得多。@Vyktor它不是DOM样式的标记。您应该如何使用DOM解析它?非常感谢。“”是正确的。但是“.”是不正确的。它用于。我怎样才能修好它?
$str=<<<STR
abc
*.some text
* some text
STR;