aspirinemaga
aspirinemaga

Reputation: 3937

Use Regular Expression to rename class

How could I use RegEx to find <a class="modal> and replace it with <a class="modal-link" ?

I tried:

preg_replace('/<a class="(.*?)">(.*?)<\/a>/i', '<a class="$1-link">$2</a>', $input);

but it's not working. Please can someone point me out to the right solution ?

By the way: I'am styling Joomla 2.5 frontpage edit content page, where the approved user can post an article. That string where i want to apply on my regex comes from:

<?php echo $this->form->getInput('image_intro', 'images'); ?>

it generates this HTML:

<a class="modal" ...>Choose</a>

Upvotes: 0

Views: 362

Answers (3)

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

There is no way of reliably, or satisfactorily, doing it using regular expressions, but if a crude search-and-replace is okay for what you are doing then it can be done:

$code = '<a class="modal">Choose</a>';
$regex = '/(?<=\sclass=")modal(?="[\s>])/';
echo preg_replace($regex, 'modal-link', $code);

There are at least two reasons that this is a bad idea, through:

  1. You should not parse or modify HTML using regular expressions. Parsing or modifying HTML is not a regular problem, it is a quite complicated and intricate problem. Using regular expressions is like using a sledgehammer when you should be using a chisel.

  2. You should not be modifying HTML code in any case. HTML should just be HTML. If you need your HTML to be different then you should change the HTML at the source, and not try to force it into shape like this.

Upvotes: 1

KryDos
KryDos

Reputation: 447

Regexp is fine. preg_replace not change $input variable.

Try

$new_string = preg_replace('/<a class="(.*?)">(.*?)<\/a>/i', '<a class="$1-link">$2</a>', $input);

But DON'T USE REGULAR EXPRESSIONS TO PARSE HTML

Upvotes: 4

nickb
nickb

Reputation: 59699

A non-regex based solution using PHP's DOMDocument class would be:

// Load up the HTML in DOMDocument
$doc = new DOMDocument;
$doc->loadHTML( '<a class="modal">Stuff</a>'); // Or: $doc->loadHTML( $this->form->getInput('image_intro', 'images'));

// Create a new XPath object to find the correct <a> tags
$xpath = new DOMXPath( $doc);

// Iterate over all <a class="modal"> tags
foreach( $xpath->query( "//a[@class='modal']") as $a) {
    // Set the class attribute correctly
    $a->setAttribute( 'class', $a->getAttribute( 'class') . '-link');
    echo $doc->saveHTML( $a); // Print the fixed <a> tag
}

This will output something similar to:

<a class="modal-link">Stuff</a>

This method is more robust and stable than a regular expression based approach, especially if you're getting HTML from user input.

Upvotes: 6

Related Questions