如何在 PHP 中将带有链接的字符串拆分为数组或对象,并丢弃所有不属于 url 的内容


How to split a string with links into an array or object in PHP and throw away all content that doesn't belong to the url?

我的数据库列中有一个链接列表,当我从数据库中抓取它时,它看起来像这样(显然,它实际上要长得多):

http://example.com/asdfasdf/erwr
http://asdfasdfas.com/asdfasd/fasdf/asdfas.mp3
http://asdfa.com/adsf/asdf/asdf/asdf.html

或者它可以看起来像这样:

http://example.com/asdfasdf/erwrhttp://asdfasdfas.com/asdfasd/fasdf/asdfas.mp3

或者它可以看起来像这样:

http://example.com/asdfasdf/erwr, http://asdfasdfas.com/asdfasd/fasdf/asdfas.mp3

所以我认为新链接的指示是开头http://除了该 url 的开头外,它可能不在 url 本身中。

因此,问题是如何在PHP中分解此列表并创建一个带有链接的数组或对象,并丢弃所有其他html,如<br>或逗号和空格等。

知道如何在 PHP 中做到这一点吗?

您可以将字符串分解为数组,并可以获取所需的字符串。例如

$url = http://example.com/asdfasdf/erwr
$string = explode('//',$url);
echo $string[1];
//output example.com/asdfasdf/erwr

我会走两步。首先使用 explode() 和 ://或类似的东西来获取以你的 url 开头的字符串,在第二步中应用正则表达式来切断第一个非 url-char(空格等)处的每个字符串。