0

I have the following code.

<a href="/29486389/Author_-_Name_of_Song.mp3/" class="popover-with-html hidden-phone">Andra - Inevitabil va fi bine.mp3</a>

How can I replace this string, using regex, but without losing a part from string. To looks like this

<a href="melodie/Author_-_Name_of_Song.mp3.html/" class="popover-with-html hidden-phone">Author - Name of Song</a>

I know i need to use a pattern like that:

$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';

Thank you very much.

2
  • 1
    Why not simply use a DOM object? Parsing html with regex is never a clean job. Commented Jun 14, 2013 at 8:17
  • You could use the following regex, note that to remove the underscore in Author - Name of Song is very difficult if not impossible with one regex (dynamically). Commented Jun 14, 2013 at 8:27

1 Answer 1

1

REGEX

<a\s+href\s*=\s*"/\d+/(.+?)_-_(.+?)\.mp3/"\s+class\s*=\s*"popover-with-html hidden-phone">.+?</a>

Regular expression image

Edit


PHP code

$pattern = '#<a\s+href="/\d+/(.+?)_-_(.+?)\.mp3/"\s+class="popover-with-html hidden-phone">.+?</a>#is';
$replacement = '<a href="melodie/$1_-_$2.mp3.html/" class="popover-with-html hidden-phone">$1 - $2</a>';

$my_clean_html_code = preg_replace($pattern, $replacement, $my_html_code);


SAMPLE OUTPUT

  • IN
<a href="/29486389/Author_-_Name_of_Song.mp3/" class="popover-with-html hidden-phone">Andra - Inevitabil va fi bine.mp3</a>
<a href="/29486389/Author2_-_sdfsd475.mp3/" class="popover-with-html hidden-phone">
   Andra - Inevitabil va fi bine.mp3
</a>
  • OUT
<a href="melodie/Authodr_-_Name_of_Song.mp3.html/" class="popover-with-html hidden-phone">Author - Name_of_Song</a>
<a href="melodie/Author2_-_sdfsd475.mp3.html/" class="popover-with-html hidden-phone">Author2 - sdfsd475</a>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, but if the name of song/author contains dots, the script doesn't work well anymore.
Is it possible to have underscores ('_') in the song/author?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.