简体   繁体   English

在PHP中的preg_match和preg_replace

[英]preg_match and preg_replace in php

I have a task to find and replace words starting and ending with "#". 我的任务是查找和替换以“#”开头和结尾的单词。

Example - my string will look like: 示例-我的字符串如下所示:

Put your hands up in the air for #performer1# , Put your hands up in the air for #event#. 举起双手来表现#performer1#,举起双手来表现#event#。

What I expect as a output is: 我期望的输出是:

Put your hands up in the air for #performer1# , Put your hands up in the air for #event# . 举起手来争夺#performer1# ,举起手来争取#event#

I have no idea about regular expressions in php, and I'm a beginner, can someone help? 我不了解php中的正则表达式,我是一个初学者,有人可以帮忙吗?

As you already suggested, the preg_replace function should do the trick. 正如您已经建议的那样, preg_replace函数应该可以解决问题。 What you now need is a regular expression like this 您现在需要的是这样的正则表达式

$string = "Put your hands up in the air for #performer#, ...";
$pattern = "/#(\w+)#/";
$replacement = '<strong>$1</strong>';
$new_string = preg_replace($pattern, $replacement, $string);

The magic bit is the $pattern variable where you specify what to look for. 神奇的一点是$pattern变量,您可以在其中指定要查找的内容。 If you put parenthesis around something, you can reference the actual contents in the $replacement variable. 如果将括号括起来,则可以在$replacement变量中引用实际内容。

The \\w+ basically says: match as many characters as possible (and at least one) that are either az , AZ , 0-9 or _ . \\w+基本上说:匹配尽可能多的字符(至少一个),它们是azAZ0-9_

The PHP PCRE Pattern Syntax can give you some more hints about how to use regular expressions. PHP PCRE模式语法可以为您提供有关如何使用正则表达式的更多提示。

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

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