Search code examples
phpregexpreg-match

PHP preg_match get content between


<!--:en-->Apvalus šviestuvas<!--:-->
<!--:ru-->Круглый Светильник<!--:-->
<!--:lt-->Round lighting<!--:-->

I need get the content between <!--:lt--> and <!--:-->

I have tried:

$string  = "<!--:en-->Apvalus šviestuvas<!--:--><!--:ru-->Круглый Светильник<!--:--><!--:lt-->Round lighting<!--:-->";
preg_match('<!--:lt-->+[a-zA-Z0-9]+<!--:-->$', $string, $match);

var_dump($match);

Something is wrong with the syntax and logic. How can I make this work?


Solution

  • preg_match("/<!--:lt-->([a-zA-Z0-9 ]+?)<!--:-->/", $string, $match);
    
    • added delimiters
    • added a match group
    • added ? to make it ungreedy
    • added [space] (there is a space in Round lighting)

    Your result should be in $match[1].


    A cooler and more generic variation is:

    preg_match_all("/<!--:([a-z]+)-->([^<]+)<!--:-->/", $string, $match);
    

    Which will match all of them. Gives:

    array(3) { [0]=> array(3) { [0]=> string(37) "Apvalus šviestuvas" [1]=> string(53) "Круглый Светильник" [2]=> string(32) "Round lighting" } [1]=> array(3) { [0]=> string(2) "en" [1]=> string(2) "ru" [2]=> string(2) "lt" } [2]=> array(3) { [0]=> string(19) "Apvalus šviestuvas" [1]=> string(35) "Круглый Светильник" [2]=> string(14) "Round lighting" } }