如何获取带有超链接的文本字符串,解开它们,然后将它们重新插入到 php 中?

发布于 2024-12-09 15:14:48 字数 258 浏览 1 评论 0原文

如果我有来自 Twitter 的一串文本,例如:

$string = "This is a link http://t.co/252351ga to follow.";

如何解开链接,然后重新插入到原始字符串中,如下所示:

$new_string = "This is a link http://www.example.org/article/23534 to follow.";

If I have a string of text from Twitter, such as:

$string = "This is a link http://t.co/252351ga to follow.";

How can I unwrap the link, and re-insert into the original string as follows:

$new_string = "This is a link http://www.example.org/article/23534 to follow.";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

成熟稳重的好男人 2024-12-16 15:14:48

这是一个由两部分组成的问题。首先,您需要一个正则表达式来查找和提取 URL。为了简单起见,最好在那里使用 preg_replace_callback 。 (如果您使用搜索,您将找到任意数量的更好的正则表达式。)

 = preg_replace_callback('#http://\S+#', "replace_url_callback", $html)

其次,您可以使用缩短的 URL 扩展服务/API,或者自己请求 URL 并检查响应中的重定向或相应的元标记。 (例如: http://jamiethompson.co.uk/web/2010/05/18/expanding-short-urls-with-php-expand_url-php-function/ - 忘记了我最近读到的服务名称。 没关系,它只是简单地称为“LongURL.org”。)

It's a two-part problem. First you need a regex to find and extract the URLs. It's best to use preg_replace_callback there for simplicity. (You'll find any number of nicer regexs, if you use the search.)

 = preg_replace_callback('#http://\S+#', "replace_url_callback", $html)

Second, you either use a shortened URL expansion service/API, or request the URLs yourself and check for redirects or the according meta tag in the response. (For example: http://jamiethompson.co.uk/web/2010/05/18/expanding-short-urls-with-php-expand_url-php-function/ - Forgot the service name I read about lately.. Nevermind, it's simply called "LongURL.org". Not affiliated.)

自找没趣 2024-12-16 15:14:48

您可能想要使用 preg_replace 之类的东西并使用模式来匹配 URL 并将匹配项替换为您自己的 URL。

编辑:
您可以在这里找到一个好的 URL 正则表达式:
http://flanders.co.nz/ 2009/11/08/a-good-url-regular-expression-repost/

然后使用如下:

$string = "This is a link http://t.co/252351ga to follow.";
$pattern = ''; //the pattern from the link
$replacement = 'http://www.example.org/article/23534';
echo preg_replace($pattern, $replacement, $string);

You probably want to use something like preg_replace and use a pattern to match URLs and replace the match with your own URL.

EDIT:
You can find a good URL regexp here:
http://flanders.co.nz/2009/11/08/a-good-url-regular-expression-repost/

Then use it as follows:

$string = "This is a link http://t.co/252351ga to follow.";
$pattern = ''; //the pattern from the link
$replacement = 'http://www.example.org/article/23534';
echo preg_replace($pattern, $replacement, $string);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文