简体   繁体   English

帮助正则表达式(PHP,preg_replace)

[英]Help with Regular expression (PHP, preg_replace)

I need to do a preg_replace on all of the PHP tags in a string, as well as any characters sitting between the PHP tags. 我需要对字符串中的所有PHP标记以及位于PHP标记之间的所有字符执行preg_replace。

Eg, if the file contents was: 例如,如果文件内容为:

Hey there!
<?php some_stuff() ?>
Woohoo!

All that should be left is: 剩下的就是:

Hey there!
Woohoo!

Here's my code: 这是我的代码:

$file_contents = file_get_contents('somefilename.php');
$regex = '#([<?php](.*)[\?>])#e';
$file_contents = preg_replace($regex, '<<GENERATED CONTENT>>', $file_contents);

FAIL. 失败。

My regular expression skills are poor, can someone please fix my regex. 我的正则表达能力很差,有人可以修复我的正则表达式。 Thank you. 谢谢。

Try this regex: 试试这个正则表达式:

#<\?.*?\?>#

Should work on short tags (without 'php') too. 应该也适用于短标签(没有'php')。

I think the main issue with your attempt was that you need to escape the question marks with backslashes, and that you were using square brackets where you shouldn't have been. 我认为尝试的主要问题是您需要用反斜杠转义问号,并且您在不应该使用的方括号中使用了方括号。 Square brackets means "pick any one of these characters". 方括号表示“选择这些字符中的任何一个”。

$regex="/<?php (.*?)?\>/"

您也可以尝试一下,这将为您工作

You can try: 你可以试试:

$regex = '#<\?php.*?\?>#i';

The regex used: <\\?php.*?\\?> 使用的正则表达式: <\\?php.*?\\?>

  • < : a literal < < :文字<
  • \\? : ? ? is a metachar to match a literal ? 是一个与文字匹配的元字符? you need to escape it. 你需要逃脱它。
  • .*? : non-greedy to match anything. :非贪婪匹配任何东西。

Use the right tool for the job. 使用正确的工具完成工作。 The PHP tokenizer contains all the functionality you need to strip PHP code away from the surrounding content: PHP令牌生成器包含将PHP代码从周围内容中剥离出来所需的全部功能:

source.php source.php

<p>Some  HTML</p>
<?php echo("hello world"); ?>
<p>More HTML</p>
<?php
/*
 Strip this out please
 */
?>
<p>Ok Then</p>

tokenize.php tokenize.php

<?php
$source = file_get_contents('source.php');
$tokens= token_get_all($source);
foreach ($tokens as $token) {
 if ($token[2] == 3 || $token[2] == 1 || $token[2] == 9) {
    echo($token[1]);
 }
}

Output: 输出:

<p>Some  HTML</p>
<p>More HTML</p>
<p>Ok Then</p>

This is a simple example. 这是一个简单的例子。 The docs list all the parser tokens you can check for. 该文档列出了您可以检查的所有解析器令牌

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

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