对于非常基本的标记,这些正则表达式是否有效?


For very basic markdown, will these regular expressions work?

只是一个关于正则表达式的快速问题:这段代码是否适用于我需要做的任何修饰?(也就是说,这是否可以安全地输入数据库?)

function markdown2html($text) {
        $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    // Strong Emphasis
    $text = preg_replace('/__(.+?)__/s', '<strong>$1</strong>', $text);
    $text = preg_replace('/'*'*(.+?)'*'*/s', '<strong>$1</strong>', $text);
    // Underline
    $text = preg_replace('/_([^_]+)_/', '<p style="text-decoration: underline;">$1</p>', $text);
    //Italic
    $text = preg_replace('/'*([^'*]+)'*/', '<em>$1</em>', $text);
    // Windows to Unix
    $text = str_replace(''r'n', ''n', $text);
    // Macintosh to Unix
    $text = str_replace(''r', ''n', $text);
    //Paragraphs
    $text = '<p>' . str_replace("'n'n", '</p><p>', $text) . '</p>';
    $text = str_replace("'n", '<br />', $text);
    // [Linked Text](Url)   
   $text = preg_replace('/'[([^']]+)]'(([a-z0-9._~:'/?#@!$&''()*+,;=%]+)')/i', '<a href="$2">$1</a>', $text);
   return $text;
}

不,绝对不行。

你的代码与SQL无关——它根本没有修改''字符。将此函数的格式化功能与SQL转义混合在一起是愚蠢的。

在某些情况下,您的代码还可能引入HTML注入——我特别怀疑URL链接正则表达式。如果没有适当的解析器,我一点也不相信它。

不能,数据通过该函数后不能保证安全。

您需要转义sql敏感字符或使用PDO/mysql。无论如何,准备好的语句要方便得多。

不要使用旧的拼凑查询的方法,例如:

$query = 'select * from table where col = '.$value;

你这是在自找麻烦。

有几件事让我眼前一亮:

我认为前两个regexs ('/__(.+?)__/s'*对应的regexs)不正确地处理__word___和***word*** -它们将把第三个字符视为单词的一部分,因此您将得到*word*(其中第一个*是粗体,最后一个不是)而不是word

关于第三个('/_([^_]+)_/'),

真的合适吗?

do _not_ do that

变成

p style=" font - family:宋体;"这样做

?

当然我是而不是说如果你解决了这些问题就可以使用