[英]Extract certain section from string
我有一个字符串,其中包含我希望在变量中提取的一段文本。 在下面的字符串中,我想用/
中提取任何内容。
$str = 'this is a random string foo/bar random - string words';
在上面的例子中,我想提取foo/bar
。 目前我通过在空格处exploding
字符串然后循环并检查每个部分是否包含/
。
$words = explode(' ', $str);
foreach($words as $word) {
if(strpos($word, '/') !== false) {
$myVar = $word;
}
}
有没有一种方法可以做到这一点,因为我需要为很多文本字符串执行此操作?
如果您确切地知道您需要匹配由/
分隔的小写字母组成的两个单词,那么多匹配正则表达式也会没问题,就像这样
preg_match_all('%[a-z]+/[a-z]+%', $subject, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
# Matched text = $result[0][$i];
}
输出: - https://eval.in/596292
但是,效率应该通过实验测试
我会使用: preg_match_all("/(\\w+\\/\\w+)[\\s|$]/", $str, $output);
现在$ output [1]是一个带匹配的数组。
模式匹配一个单词后跟斜线然后再单词,然后它需要一个空格或字符串结尾。 这意味着它不匹配字符串,如:
last/string/to/test
那么,最好的解决方案就是正则表达式,正如其他人所说的那样。 但是你必须清楚你想要匹配的东西 ,例如'带有/在其中的任何东西'将匹配你的整个句子。 我想在你的情况下最容易说出一切但是空白:
<?php
$str = 'this is a random string foo/bar random - string words - another/example';
preg_match_all('#[^ ]+\/[^ ]+#', $str, $matches);
var_dump($matches);
array(1){[0] => array(2){[0] => string(7)“foo / bar” 1 => string(15)“another / example”}}
当然,这在某种程度上是个人品味的问题,如果我想以贪婪的方式捕捉某些东西,我宁愿通过排除来提取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.