How to extract all the substrings between single quotation marks in PHP

1 Answer

0 votes
function extract_substrings($s) {
    // Regular expression pattern to find substrings between single quotation marks
    $pattern = "/'(.*?)'/";
    
    // Find all matches in the input string
    preg_match_all($pattern, $s, $matches);
    
    if (empty($matches[1])) {
        return "";
    }
    
    return $matches[1];
}

$s = "PHP 'general-purpose' 'scripting' 'language'";

$result = extract_substrings($s);

print_r($result);


   
/*
run:
    
Array
(
    [0] => general-purpose
    [1] => scripting
    [2] => language
)


*/

 



answered Feb 12, 2025 by avibootz
...