[英]PHP determine if the word is in quotation marks
How do I get PHP to tell if a word is inside quotation marks?如何让 PHP 判断一个单词是否在引号内?
Example: Hi there, "my" name is ...示例:您好,“我的”名字是...
How do I find out if the word my is in quotation marks (double or single)?如何确定单词 my 是否在引号中(双引号或单引号)?
<?php
if(isset($_POST['sub'])) {
$str = $_POST['textarea'];
// determine if the word "my" is in quotation marks from the $str
}
You want a regular expression that can detect the word you're searching for, wrapped in consistent quotes (same quote character each side).您需要一个正则表达式,它可以检测您正在搜索的单词,并用一致的引号括起来(每边相同的引号字符)。
Something like this像这样的东西
$word = 'my';
$quoteCharacters = ['"', "'"];
$expression = sprintf('/([%s])%s\1/i',
implode($quoteCharacters), preg_quote($word));
// produces something like /(["'])my\1/i
if (preg_match($expression, $str)) {
echo "Found '$word' quoted";
}
The \\1
is aback reference to match the same quote character as found previously. \\1
是一个反向引用,用于匹配之前找到的相同引号字符。
Demo ~ https://3v4l.org/juHIi演示 ~ https://3v4l.org/juHIi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.