Wizard
Wizard

Reputation: 11265

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?

Upvotes: 0

Views: 144

Answers (2)

Halcyon
Halcyon

Reputation: 57709

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" } }

Upvotes: 2

Nambi
Nambi

Reputation: 12042

Use this Pattern (?<=<!--:lt-->)(.*)(?=<!--:-->)

<?php
$string  = "<!--:en-->Apvalus šviestuvas<!--:--><!--:ru-->Круглый Светильник<!--:--><!--:lt-->Round lighting<!--:-->";
preg_match('~(?<=<!--:lt-->)(.*)(?=<!--:-->)~', $string, $match);

var_dump($match);

Upvotes: 0

Related Questions