Using preg_match to find a group in a string?
I'm trying to find special characters with characters like <开发者_JAVA百科?
, <?php
, or ?>
in a string. The code below works to find "php" in the string anywhere no matter if it's PHP
, php
, or phpaPHPa
.
<?php
$searchfor = "php";
$string = "PHP is the web scripting language of choice.";
if (preg_match("/".$searchfor."/i", $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
I need a similar code that finds special characters like <?
, <?php
, or ?>
in the string. Any suggestions?
You can use same code. Just make sure to escape regex special characters when using them in matching. The question mark must be escaped so your $searchfor
becomes <\?php
Using strpos (or stripos) will be faster than using RegEx'es...
if(false === strpos($text, '<?'))
echo 'Match was not found';
else
echo 'Match was found';
精彩评论