【问题标题】:Parse soundcloud "/sets/" url with Regular Expressions in PHP在 PHP 中使用正则表达式解析 soundcloud “/sets/” url
【发布时间】:2014-05-31 05:53:40
【问题描述】:

我正在尝试使用正则表达式将 soundcloud 解析为从链接中提取的嵌入代码

到目前为止,如果我输入此网址:https://soundcloud.com/theredrojomusic/animal,它首先转换为链接,然后更改为嵌入代码(采用 vimeo/youtube/metacafe 正则表达式):

array(
   'https{0,1}:\/\/w{0,3}\.*soundcloud\.com\/([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)[^< ]*',
   '<iframe width="100%" height="'.$s.'" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=http://soundcloud.com/$1/$2&amp;auto_play=false&hide_related=true&show_comments=false&show_user=true&show_reposts=false&visual=false"></iframe>')

问题是当我尝试解析如下集合时:https://soundcloud.com/theredrojomusic/sets/tristezza

这只是将 url 呈现为 https://soundcloud.com/theredrojomusic/sets 并且嵌入代码无法处理。

我试过了:

array(
    'https{0,1}:\/\/w{0,3}\.*soundcloud\.com\/([A-Za-z0-9_-])\/sets\/*([A-Za-z0-9_-]+)[^< ]*',
    '<iframe width="100%" height="'.$s.'" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=http://soundcloud.com/$1/sets/$2&amp;auto_play=false&hide_related=true&show_comments=false&show_user=true&show_reposts=false&visual=false"></iframe>'), 

但是渲染出来的url是https://soundcloud.com/c/sets/tristezza

我想要两个正则表达式,一个用于非/sets/ url,另一个用于/sets/,因为嵌入代码有点不同(至少如果我希望/sets/ 看起来像一个列表而不是列表只是一首歌。)

我真的很不擅长正则表达式...有人能指出我正确的方向吗?

谢谢

【问题讨论】:

    标签: php regex


    【解决方案1】:

    第一个正则表达式是

    https{0,1}:\/\/w{0,3}\.*soundcloud\.com\/([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)[^< ]*
    

    soundcloud\.com 之后有两个正斜杠,后跟字母数字序列。因此它可以匹配soundcloud.com/wordOne/wordTwo。不匹配的集合(即https://soundcloud.com/theredrojomusic/sets/tristezza)看起来像soundcloud.com/wordOne/wordTwo/wordThree

    这两个示例没有显示所需文本后面的字符,但是第一个正则表达式的最后一部分是[^&lt; ]*,它没有任何用处。它说寻找零个或多个不是左雪佛龙或空格的字符,但它对它们没有任何作用。假设左 V 形或空格标记所需文本的结尾,然后将正则表达式更改为

    https{0,1}:\/\/w{0,3}\.*soundcloud\.com\/([A-Za-z0-9_-\/]+)[< ]
    

    甚至

    https{0,1}:\/\/w{0,3}\.*soundcloud\.com\/([^< ]+)[< ]
    

    首先查找任何字母数字加正斜杠后跟左 V 形或空格的序列。第二个查找除左 V 形或空格之外的任何字符序列。如果没有更准确地说明需要什么,就很难说出需要什么正则表达式。

    稍后在这两段代码中都有一个src=... 子句。其中有一个$1/$2,需要更改为$1

    更新

    要匹配带有和不带有/sets/ 的字符串,我建议使用上面给出的表达式,这将找到两个版本。然后使用if 语句检查匹配的文本是否包含/sets/

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    相关资源
    最近更新 更多