replacing a custom tag's value with a string in php
I want to read a html file and replace what ever is inside mytag.
so in html file we have something like this :
<div>
<h3><mytag>_THIS_DAY</mytag></h3>
开发者_如何学Python <div>
[LOGIN]
</div>
</div>
and then in php file , i need to read the file and replace the values inside tags.
str_replace() ?
how to get the value inside those tags in php and then how to replace them with something like a string ?
str_replace() uses regular expressions, which (as noted elsewhere on this site) are usually insufficient for parsing HTML.
You should use an HTML parser to retrieve and/or replace the required values.
Warning: You shouldn't parse XHTML with regexp
That said, you can still do it:
preg_replace("~(?<=<mytag>)[^>]+(?=</mytag>)~", "independance day", $yourHtml);
Quick explanation:
[^>]+We look for a string of 1+ char and without>(?<=<mytag>)This string must be after<mytag>(positive lookahead)(?=</mytag>)This string must be folowed by</mytag>(positive lookbehind)
Live example
- take a look in the php-manual fpr preg_replace. with a regex you can perform a simple replacement
- if you want to something more complex, you can parse your html. you can use for example the simple_html_dom-contribution: http://simplehtmldom.sourceforge.net/
加载中,请稍侯......
精彩评论