How to use preg_match () to get a link inside a Javascript code

0

Hello, I'm doing a file_get_contents() in PHP and getting a JS, in that javascript has a code where it contains:

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

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

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

But it is not working, is returning empty, who can help, I would be grateful!

    
asked by anonymous 01.08.2018 / 01:25

2 answers

4

You can check out: link

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


array(2
0   =>  $("#download-botao").attr("href", "link.com");
1   =>  link.com
)
    
01.08.2018 / 01:45
4

Instead of putting the entire string in Regex, you can put only the part that interests you by taking Group 1, which is what is in the last couple of quotes:

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

Try IDEONE

Regex explanation:

,          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 \
    
01.08.2018 / 02:05