Php 在不使用正则表达式的情况下获取字符串特定部分的最简单方法是什么?

Php 在不使用正则表达式的情况下获取字符串特定部分的最简单方法是什么?,php,Php,我经常需要分离字符串的某个部分,但不擅长正则表达式。是的,我应该在这方面做得更好,但同时,我想知道你觉得做以下事情的最好方法是什么 我有一些随机的文本,通常是标签,我需要从中分离出一个片段。大概是这样的: <title>Ask a Question - Stack Overflow</title> <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico"

我经常需要分离字符串的某个部分,但不擅长正则表达式。是的,我应该在这方面做得更好,但同时,我想知道你觉得做以下事情的最好方法是什么

我有一些随机的文本,通常是标签,我需要从中分离出一个片段。大概是这样的:

<title>Ask a Question - Stack Overflow</title>
<link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
<link rel="apple-touch-icon" href="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png">
<link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.sstatic.net/js/stub.js?v=a1714a379225"></script>
<link rel="stylesheet" type="text/css" href="http://cdn.sstatic.net/stackoverflow/all.css?v=bd607061c911">
提问-堆栈溢出
从这里,我需要得到“苹果触摸图标”的URL。我会这样做:

<?php
// $text contains the previous blurb

// This returns an array, with the second item starting with the necessary text
$explode = explode('apple-touch-icon" href=",$text);

// This returns the position of the `"`, which is what marks the end of the string
$end_of_string = strpos('"',$explode[1]);

// Now I get only this particular part of the string
$return = substr($explode,0,$end_of_string);
?>
尝试使用PHP strstr()函数

事后看来(现在编辑),我不确定这是你想要的。您可以使用它来隔离字符串的某些片段,但它不会比正则表达式更快/更容易


PHP str*()函数系列无疑是一个正确的起点,但我绝对建议您重新学习正则表达式,而不是寻找其他不太理想的解决方案。

我强烈建议您学习正则表达式,它非常有帮助,而且不难学

如果没有正则表达式,请看一下

,strtok()似乎就是您所追求的

但你的问题是“我不想要一个好的解决方案,我想从最坏的中选择”。
所以,这毫无意义-1

如果你在解析HTML,你应该使用解析HTML的东西,而不是正则表达式或字符串搜索…也就是说,考虑到你的示例数据和你想要避免正则表达式的愿望,你可以只使用strpos…我宁愿使用strpos而不是explode,因为它创建了一种使用模式,可以更好地传达你的意图

int strpos(字符串$haystack,混合$needle[,int$offset=0])

$index = strpos($text, "apple-touch-icon");
$index = strpos($text, "href=", $index);
 ...
$return = substr($text, $index, $end-of-string);