如何匹配字符串中的模式

时间:2022-09-13 07:35:16

String

$x= "SDGH <fn>xyz("|",YAG);</fn> is right ";
$code = ?? ;
eval($code);

I have to get the code which is inside the tag and execute it .

我必须得到标签内的代码并执行它。

Thanks

谢谢

2 个解决方案

#1


2  

The best way to achieve this would probably be using regular expressions. If you want to learn more about regex, check out this tutorial.

实现这一目标的最佳方法可能是使用正则表达式。如果您想了解有关正则表达式的更多信息,请查看本教程。

if(preg_match("/<fn>(.*)<\/fn>/",$x, $matches))
    $code = $matches[1];

This code matches everything inbetween <fn> and </fn>. Bear in mind that using eval is always dangerous whenever user input is involved. In that case, you'd need to make sure that only certain code is allowed to execute.

此代码匹配 和 之间的所有内容。请记住,只要涉及用户输入,使用eval始终是危险的。在这种情况下,您需要确保只允许执行某些代码。

#2


0  

You don't need regex, you can also get it with string function.

你不需要正则表达式,你也可以使用字符串函数。

$input = 'SDGH <fn>xyz("|",YAG);</fn> is right';
$output = substr($input, strpos($input, '<fn>') + 4);
$output = substr($output, 0, strpos($output, '</fn>'));
echo $output;

There're many ways to get this result, you can use regex, string functions, even explode

有很多方法可以获得这个结果,你可以使用正则表达式,字符串函数,甚至爆炸

#1


2  

The best way to achieve this would probably be using regular expressions. If you want to learn more about regex, check out this tutorial.

实现这一目标的最佳方法可能是使用正则表达式。如果您想了解有关正则表达式的更多信息,请查看本教程。

if(preg_match("/<fn>(.*)<\/fn>/",$x, $matches))
    $code = $matches[1];

This code matches everything inbetween <fn> and </fn>. Bear in mind that using eval is always dangerous whenever user input is involved. In that case, you'd need to make sure that only certain code is allowed to execute.

此代码匹配 和 之间的所有内容。请记住,只要涉及用户输入,使用eval始终是危险的。在这种情况下,您需要确保只允许执行某些代码。

#2


0  

You don't need regex, you can also get it with string function.

你不需要正则表达式,你也可以使用字符串函数。

$input = 'SDGH <fn>xyz("|",YAG);</fn> is right';
$output = substr($input, strpos($input, '<fn>') + 4);
$output = substr($output, 0, strpos($output, '</fn>'));
echo $output;

There're many ways to get this result, you can use regex, string functions, even explode

有很多方法可以获得这个结果,你可以使用正则表达式,字符串函数,甚至爆炸