2

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>
                        <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 ?

Mac Taylor
  • 5,020
  • 14
  • 50
  • 73

3 Answers3

2

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.

Community
  • 1
  • 1
George Cummins
  • 28,485
  • 8
  • 71
  • 90
2

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

Community
  • 1
  • 1
Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
1
  • 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/
0xDEADBEEF
  • 3,401
  • 8
  • 37
  • 66