SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Function Curry'er JimmyP's Avatar
    Join Date
    Aug 2007
    Location
    Brighton, UK
    Posts
    2,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Need to insert something into string - just before last tag

    I have a string with a bunch of HTML tags in. I want to insert something just before the very last tag finishes.

    E.g.

    This is the string:

    Code PHP:
    $string = '<p><strong>HELLO</strong></p>';

    I need to insert a link just before the last tag:

    <p><strong>HELLO</strong><a href="#">The link</a></p>

    The last tag is not always a </p> so I guess some regular expression will need to be used.

    Any help is appreciated!
    James Padolsey
    末末末末末末末末末末末末末末末末末末末
    Awesome JavaScript Zoomer (demo here)
    'Ajaxy' - Ajax integration solution (demo here)

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    $string '<p><strong>HELLO</strong></p>';
    $foo '...link...';

    echo 
    preg_replace('#(.*)(</[a-z]+>)#si''$1' $foo '$2'$string); 
    This will insert before the last stand alone closing tag. Consider what you want to happen for self closing tags like <img> or <img />
    PHP Code:
    $string '<p><strong>HELLO</strong></p><img src="foo">'

  3. #3
    SitePoint Zealot
    Join Date
    May 2007
    Posts
    109
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code HTML4Strict:
     
    $string = '<p><strong>HELLO</strong></p>';
    $add = '<a href="#">The link</a>';
     
    preg_match('ァ<[^>]+>(.*)<[^>]+>ァ', $string, $matches);
    $new_string = str_replace($matches[1], $matches[1].$add, $string);
    echo $new_string;

    Hope this helps...

  4. #4
    Function Curry'er JimmyP's Avatar
    Join Date
    Aug 2007
    Location
    Brighton, UK
    Posts
    2,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That works perfectly! Thank you.

    That's a good point about self closing tags. I think maybe if it looked for the last closing tag (in your example, that would be the </p> just before the <img/>.

    So it would go from this:
    <p><strong>HELLO</strong></p><img src="foo">

    To this:
    <p><strong>HELLO</strong><a href="#">My link</a></p><img src="foo">
    James Padolsey
    末末末末末末末末末末末末末末末末末末末
    Awesome JavaScript Zoomer (demo here)
    'Ajaxy' - Ajax integration solution (demo here)


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
  •