php 如何在PHP中的两个字符串之间获取子字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5696412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:15:14  来源:igfitidea点击:

How to get a substring between two strings in PHP?

phpsubstring

提问by Nadjib Mami

I need a function that returns the substring between two words (or two characters). I'm wondering whether there is a php function that achieves that. I do not want to think about regex (well, I could do one but really don't think it's the best way to go). Thinking of strposand substrfunctions. Here's an example:

我需要一个函数来返回两个单词(或两个字符)之间的子字符串。我想知道是否有一个 php 函数可以实现这一点。我不想考虑正则表达式(好吧,我可以做一个,但真的不认为这是最好的方法)。思维strpossubstr功能。下面是一个例子:

$string = "foo I wanna a cake foo";

We call the function: $substring = getInnerSubstring($string,"foo");
It returns: " I wanna a cake ".

我们调用这个函数:$substring = getInnerSubstring($string,"foo");
它返回:“我想要一个蛋糕”。

Thanks in advance.

提前致谢。

Update:Well, till now, I can just get a substring beteen two words in just one string, do you permit to let me go a bit farther and ask if I can extend the use of getInnerSubstring($str,$delim)to get any strings that are between delim value, example:

更新:嗯,到目前为止,我只能在一个字符串中获得两个单词之间的子字符串,您是否允许让我走得更远,并询问我是否可以扩展使用getInnerSubstring($str,$delim)以获取 delim 值之间的任何字符串,例子:

$string =" foo I like php foo, but foo I also like asp foo, foo I feel hero  foo";

I get an array like {"I like php", "I also like asp", "I feel hero"}.

我得到一个像{"I like php", "I also like asp", "I feel hero"}.

回答by Alejandro García Iglesias

If the strings are different (ie: [foo] & [/foo]), take a look at this postfrom Justin Cook. I copy his code below:

如果字符串不同(即:[foo] & [/foo]),请查看Justin Cook 的这篇文章。我复制他的代码如下:

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');

echo $parsed; // (result = dog)

回答by nkkollaw

Regular expressions is the way to go:

正则表达式是要走的路:

$str = 'before-str-after';
if (preg_match('/before-(.*?)-after/', $str, $match) == 1) {
    echo $match[1];
}

onlinePhp

在线PHP

回答by daniel

function getBetween($string, $start = "", $end = ""){
    if (strpos($string, $start)) { // required if $start not exist in $string
        $startCharCount = strpos($string, $start) + strlen($start);
        $firstSubStr = substr($string, $startCharCount, strlen($string));
        $endCharCount = strpos($firstSubStr, $end);
        if ($endCharCount == 0) {
            $endCharCount = strlen($firstSubStr);
        }
        return substr($firstSubStr, 0, $endCharCount);
    } else {
        return '';
    }
}

Sample use:

样品用途:

echo getBetween("abc","a","c"); // returns: 'b'

echo getBetween("hello","h","o"); // returns: 'ell'

echo getBetween("World","a","r"); // returns: ''

回答by Christian

function getInnerSubstring($string,$delim){
    // "foo a foo" becomes: array(""," a ","")
    $string = explode($delim, $string, 3); // also, we only need 2 items at most
    // we check whether the 2nd is set and return it, otherwise we return an empty string
    return isset($string[1]) ? $string[1] : '';
}

Example of use:

使用示例:

var_dump(getInnerSubstring('foo Hello world foo','foo'));
// prints: string(13) " Hello world "

If you want to remove surrounding whitespace, use trim. Example:

如果要删除周围的空格,请使用trim. 例子:

var_dump(trim(getInnerSubstring('foo Hello world foo','foo')));
// prints: string(11) "Hello world"

回答by Ravi Verma

function getInbetweenStrings($start, $end, $str){
    $matches = array();
    $regex = "/$start([a-zA-Z0-9_]*)$end/";
    preg_match_all($regex, $str, $matches);
    return $matches[1];
}

for examle you want the array of strings(keys) between @@ in following example, where '/' doesn't fall in-between

例如,在以下示例中,您需要 @@ 之间的字符串(键)数组,其中 '/' 不在中间

$str = "C://@@ad_custom_attr1@@/@@upn@@/@@samaccountname@@";
$str_arr = getInbetweenStrings('@@', '@@', $str);

print_r($str_arr);

回答by ragnar

I like the regular expression solutions but none of the others suit me.

我喜欢正则表达式解决方案,但其他解决方案都不适合我。

If you know there is only gonna be 1 result you can use the following:

如果您知道只有 1 个结果,您可以使用以下命令:

$between = preg_replace('/(.*)BEFORE(.*)AFTER(.*)/sm', '', $string);

Change BEFORE and AFTER to the desired delimiters.

将 BEFORE 和 AFTER 更改为所需的分隔符。

Also keep in mind this function will return the whole string in case nothing matched.

还要记住,如果没有匹配项,此函数将返回整个字符串。

This solution is multiline but you can play with the modifiers depending on your needs.

此解决方案是多行的,但您可以根据需要使用修饰符。

回答by Bryce

use strstr php function twice.

使用 strstr php 函数两次。

$value = "This is a great day to be alive";
$value = strstr($value, "is"); //gets all text from needle on
$value = strstr($value, "be", true); //gets all text before needle
echo $value;

outputs: "is a great day to"

输出: "is a great day to"

回答by Light93

Not a php pro. but i recently ran into this wall too and this is what i came up with.

不是 php 专业人士。但我最近也碰到了这堵墙,这就是我想出来的。

function tag_contents($string, $tag_open, $tag_close){
   foreach (explode($tag_open, $string) as $key => $value) {
       if(strpos($value, $tag_close) !== FALSE){
            $result[] = substr($value, 0, strpos($value, $tag_close));;
       }
   }
   return $result;
}

$string = "i love cute animals, like [animal]cat[/animal],
           [animal]dog[/animal] and [animal]panda[/animal]!!!";

echo "<pre>";
print_r(tag_contents($string , "[animal]" , "[/animal]"));
echo "</pre>";

//result
Array
(
    [0] => cat
    [1] => dog
    [2] => panda
)

回答by Asif Rahman

<?php
  function getBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
  }
?>

Example:

例子:

<?php 
  $content = "Try to find the guy in the middle with this function!";
  $start = "Try to find ";
  $end = " with this function!";
  $output = getBetween($content,$start,$end);
  echo $output;
?>

This will return "the guy in the middle".

这将返回“中间人”。

回答by oblig

If you're using fooas a delimiter, then look at explode()

如果您foo用作分隔符,请查看explode()