在Javascript代码中使用preg_match_all匹配

时间:2015-11-11 03:49:28

标签: javascript php regex

我通过使用preg_match_all函数在我的WordPress帖子中获取SoundCloud音频网址,在PHP中创建了一个正则表达式。正则表达式正常运行没有任何问题:

preg_match_all[0][0] = https://soundcloud.com/anevo-remix/h3llo-anevo-remix-final

当我尝试preg_match_all[0][0]播放器没有加载时,但是当我放置https://soundcloud.com/anevo-remix/h3llo-anevo-remix-final网址时,播放器加载没有任何问题。如何使用PHP代码加载播放器?

<?php
    $soundcloud_pattern = "/((http:\/\/(soundcloud\.com\/.*|soundcloud\.com\/.*\/.*|soundcloud\.com\/.*\/sets\/.*|soundcloud\.com\/groups\/.*|snd\.sc\/.*))|(https:\/\/(soundcloud\.com\/.*|soundcloud\.com\/.*\/.*|soundcloud\.com\/.*\/sets\/.*|soundcloud\.com\/groups\/.*)))/i";
    if(preg_match_all($soundcloud_pattern, $subject, $soundcloud_audio_url)) {
    var_dump($soundcloud_audio_url);
    echo ' 
    <script src="https://connect.soundcloud.com/sdk/sdk-3.0.0.js"></script>
    <div id="soundcloud-audio"></div>
    <script type="text/JavaScript">
        SC.oEmbed("'.$soundcloud_audio_url[0][0].'", {
            element: document.getElementById("soundcloud-audio")
        });
    </script>';
}
?>

1 个答案:

答案 0 :(得分:2)

试试这样。我也认为没有理由使用preg_match_all

<?php
$soundcloud_pattern = "/((http:\/\/(soundcloud\.com\/.*|soundcloud\.com\/.*\/.*|soundcloud\.com\/.*\/sets\/.*|soundcloud\.com\/groups\/.*|snd\.sc\/.*))|(https:\/\/(soundcloud\.com\/.*|soundcloud\.com\/.*\/.*|soundcloud\.com\/.*\/sets\/.*|soundcloud\.com\/groups\/.*)))/i";
if (preg_match($soundcloud_pattern, $subject, $soundcloud_audio_url)) : ?>
<script src="https://connect.soundcloud.com/sdk/sdk-3.0.0.js"></script>
<div id="soundcloud-audio"></div>
<script>
SC.oEmbed(<?= json_encode(trim($soundcloud_audio_url[0])) ?>, {
    element: document.getElementById("soundcloud-audio")
});
</script>
<?php endif ?>