SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Oct 2008
    Posts
    295
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help with regular exression

    Hi,
    I have some predefined HTML where I need to replace certain patterns depending of the value of $key. Here is small sample of that html and also the regular expression pattern I have tried to apply to it without success so far. Anyone there who could help out with proper pattern? What I am doing wrong in this current because it does not match? What it should do is replace some of the <tr></tr> elements with a newline.

    HTML Code:
    <tr>
    <td>[:some_tag:]</td>
    <td> some text </td>
    </tr>
    <tr>
    <td> [:another_tag:] </td>
    <td> another text </td>
    </tr>
    PHP Code:
    $pregSearch[] = '/(\r?\n)<tr>\r?\n<td>.*\[:'$key .':\].*<\/td>\r?\n<td>.*<\/td>\r?\n<\/tr>\r?\n/';
    $pregReplace[] = '$1'

  2. #2
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,398
    Mentioned
    65 Post(s)
    Tagged
    1 Thread(s)
    Your pattern asks for a new line at the start and end of the tr elements. So if you're testing it with the HTML string from your post; there will be no initial new line, no double new line (your pattern would need two new lines) between the tr elements, and no final new line at the end of the second tr. As such, it will fail (as you know already).

    It might also be a good idea to use preg_quote around your $key when using it as part of a regular expression pattern.
    Salathe
    Software Developer and PHP Manual Author.

  3. #3
    SitePoint Addict
    Join Date
    Oct 2008
    Posts
    295
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well I have tried a lot of different variations of that pattern, also without the starting and ending newlines without success so I am looking for if someone who knows more about regexp's would fix it. There can also be dozens of similar <tr> -elements in a row in the actual code I just took few for the example to make it shorter.

    What comes the the preg_quote, I did not even know that kind of function existed! I have used addcslashes() before and added the escaped characters as parameter for it before using in regexp's. preg_quote is nice and will come handy. Thanks!

    ..continues struggling with the pattern

  4. #4
    SitePoint Addict
    Join Date
    Oct 2008
    Posts
    295
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Problem solved, I actually had the pattern stuff in wrong order compared to the actual html code.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •