如何获取带有超链接的文本字符串,解开它们,然后将它们重新插入到 php 中?
如果我有来自 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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个由两部分组成的问题。首先,您需要一个正则表达式来查找和提取 URL。为了简单起见,最好在那里使用 preg_replace_callback 。 (如果您使用搜索,您将找到任意数量的更好的正则表达式。)
其次,您可以使用缩短的 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.)
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.)您可能想要使用 preg_replace 之类的东西并使用模式来匹配 URL 并将匹配项替换为您自己的 URL。
编辑:
您可以在这里找到一个好的 URL 正则表达式:
http://flanders.co.nz/ 2009/11/08/a-good-url-regular-expression-repost/
然后使用如下:
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: