Reputation: 119
I'm working on a multi platform application and I have to use preg_match_all function in php but I couldn't use it in proper way.
<div id="menu_background" style="background-image:url(images/menu_back_aylik.png);width:279px;height:164px;">
<div id="menu_header"><div class="one_menu_date" style="margin-left:94px;">**Çrş. 10.07.2013**</div>
<div onclick="next();" id="nextMenu"></div>
</div>
<div id="menu_container" style="margin-left:30px;margin-top:16px;">
<div id="menu_slider" style="width:17889px;">
<div class="one_menu">
<div class="one_lunchMainMenu">**lunch menu**</div>
<div class="one_lunchAltMenu">**lunch menu alternative**</div>
<div class="one_dinnerMainMenu">**dinner menu**</div>
<div class="one_dinnerAltMenu">**dinner menu alternative**</div>
</div>
</div>
</div>
10.07.2013 is today's date
I want to assign lunch menu to $lunch, lunch menu alternative to $lunch_a but i don't know much about preg_match_all.
Can someone help me?
edit: I'm trying to get lunch menu from another website
edit2: I'm having trouble with regex
Upvotes: 0
Views: 78
Reputation: 119
I've solved my problem :
$str=file_get_contents('target url');
preg_match_all('#<div id="menu_background"(.*?)>(.*?)<div class="one_menu_date"(.*?)>(.*?)'.date("d").'(.*?)'.date("m").'(.*?)'.date("Y").'</div>(.*?)<div class="one_lunchMainMenu">(.*?)</div>(.*?)<div class="one_lunchAltMenu">(.*?)</div>(.*?)<div class="one_dinnerMainMenu">(.*?)</div>(.*?)<div class="one_dinnerAltMenu">(.*?)</div>(.*?)</div>(.*?)</div>(.*?)</div>(.*?)</div>#si',$str,$aaa);
Upvotes: 0
Reputation: 89547
A good way is to use xpath to extract the datas:
$doc = new DOMDocument();
@$doc->loadHTMLFile($url);
$xpath = new DOMXPath($doc);
$lunches = $xpath->query("//div[@class='one_lunchMainMenu']/text()|//div[@class='one_lunchAltMenu']/text()");
foreach($lunches as $lunch) {
echo '<br>'. $lunch->nodeValue; }
Upvotes: 0
Reputation: 4592
I'm a little confused what you're doing here. It looks like you're trying to replace lunch menu with a PHP variable called $lunch.
Are you just writing a PHP page that needs dynamic HTML generation? If so, you shouldn't need preg_match_all. You should be able to do this:
<div class="one_lunchMainMenu"><?php echo $lunch; ?></div>
That dynamically injects the value of $lunch into the code.
The only reason I can think of that you might need to use preg_match_all is if you have this HTML code handed to you in a variable rather than writing it yourself, and you're trying to replace parts of the code with preg_match_all.
EDIT:
After seeing your comment, it looks like you really do need to replace data in a string of HTML, rather than dynamically generating it on the fly.
Since you're trying to do a replace, I would use the preg_replace
function instead:
$escaped_val = preg_quote("**lunch menu**") # Need to escape this string because it contains usual regex special chars
preg_replace( /$escapedVal/, $lunch, $yourHTMLString )
Upvotes: 1