Reputation: 310
I'm created a regex in PHP by using the preg_match_all
function to get a SoundCloud audio url within my WordPress post. The regex works correctly without any problem:
preg_match_all[0][0] = https://soundcloud.com/anevo-remix/h3llo-anevo-remix-final
When I try the preg_match_all[0][0]
the player doesn't load, but when I put the https://soundcloud.com/anevo-remix/h3llo-anevo-remix-final
url, the player loads without any problem. How can I use the PHP code such that the player loads?
<?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>';
}
?>
Upvotes: 2
Views: 610
Reputation: 164980
Try like this. I also see no reason to use 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 ?>
Upvotes: 2