简体   繁体   中英

PHP determine if the word is in quotation marks

How do I get PHP to tell if a word is inside quotation marks?

Example: Hi there, "my" name is ...

How do I find out if the word my is in quotation marks (double or single)?

<?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.

Demo ~ https://3v4l.org/juHIi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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