简体   繁体   English

如何使用正则表达式将文本样式更改为特定样式?

[英]How to change the style of a text to a particular pattern using regex?

I have a textarea like what is in stackoverflow's ask-page. 我有一个像stackoverflow的Ask-Page中一样的文本区域。 Now I want to replace some text to some specific pattern. 现在,我想将某些文本替换为某些特定模式。 In other word I want to add some tags around a text. 换句话说,我想在文本周围添加一些标签。 I want something like these: 我想要这样的东西:

**bold**
__underline__
*italics*
--strike--
[linkname](www.example.com)

Well, I'm newbie to PHP... But I did it using javascript: 好吧,我是PHP的新手...但是我使用javascript做到了:

text.replace(/\*\*(.*?)\*\*/g, "<b>$1</b>");
text.replace(/__(.*?)__/g, "<u>$1</u>");
text.replace(/\*(.*?)\*/g, "<i>$1</i>");
text.replace(/--(.*?)--/g, "<del>$1</del>");

// also I didn't know do that for link-href
// I want this: <a href="www.example.com">linkname</a>

So, how can I do that using php? 那么,如何使用php做到这一点? (I want to check the content both client-side and server-side, Because maybe javacript is deactivate on some of visitor's system) (我想检查客户端和服务器端的内容,因为也许在某些访问者的系统上javacript被禁用了)

For PHP there is a function called preg_replace , this is the one you are searching for. 对于PHP,有一个名为preg_replace的函数,这是您要搜索的函数。

For your second problem with the link, you could do something like this, this makes a simple check, to be sure that the URL is valid. 对于链接的第二个问题,您可以执行类似的操作,从而进行简单的检查,以确保URL有效。
(?:^\\[)(.*?)(?:\\]\\()(www\\..+?\\.\\D+?)(?:\\))

UPDATE 1: 更新1:
Simple use with my regex as requested: 根据要求与我的正则表达式一起简单使用:
<?php $string = '[linkname](www.example.com)'; $pattern = '/(?:^\\[)(.*?)(?:\\]\\()(www\\..+?\\.\\D+?)(?:\\))/'; $replacement = '${1}, $2'; echo preg_replace($pattern, $replacement, $string);

For doing all of this easier you can use this PHP class: (Suggested by @miken32): 为了使所有这些工作更容易,您可以使用以下PHP类:(由@ miken32建议):
https://github.com/erusev/parsedown/blob/master/Parsedown.php#L1171 https://github.com/erusev/parsedown/blob/master/Parsedown.php#L1171

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM