How to use preg_match() to catch a link within a Javascript code

Asked

Viewed 225 times

0

Hello, I’m making one file_get_contents() in PHP and getting a JS, in this javascript has a code where it contains:

$("#download-botao").attr("href", "link.com");

I’m wanting to get this link.com in my PHP, I’m trying through preg_match(), with the following code:

preg_match('/$("#download-botao").attr("href", "(.*?)");/', $url, $final);

however is not working, is returning Empty, who can help, would be grateful!

2 answers

4


You can check in: https://www.phpliveregex.com/p/oLJ

\$\("#download-botao"\)\.attr\("href", "(.*)"\);


array(2
0   =>  $("#download-botao").attr("href", "link.com");
1   =>  link.com
)

4

Instead of putting the whole string in Regex, you can put only the part that matters by taking group 1, which is what is between the last pair of quotes:

<?php
$url = '$("#download-botao").attr("href","link.com");';
preg_match('/,\s?"(.+?)"\);/', $url, $final);
echo $final[1]; // link.com
?>

Testing at IDEONE

Explanation by Regex:

,          tem uma vírgula antes
\s?        tem um espaço ou não após a vírgula e antes das aspas
"(.+?)"    qualquer coisa entre as aspas
\);        tem parênteses e um ponto e vírgula após a segunda aspas,
           onde o parênteses deve ser escapado com a barra invertida \

Browser other questions tagged

You are not signed in. Login or sign up in order to post.