如何在 PHP 中获取两个字符串之间的子字符串? [英] How to get a substring between two strings in PHP?

查看:41
本文介绍了如何在 PHP 中获取两个字符串之间的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 strpos and substr functions. Here's an example:

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

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

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

更新:好吧,到目前为止,我只能在一个字符串中得到两个单词之间的子字符串,你允许我走远一点,问我是否可以扩展 getInnerSubstring($str,$delim)<的使用/code> 获取任何介于 delim 值之间的字符串,例如:

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:

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

我得到一个数组,如 {我喜欢 php"、我也喜欢 asp"、我觉得英雄"}.

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

推荐答案

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

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

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)

这篇关于如何在 PHP 中获取两个字符串之间的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆