How to get a substring between two strings in PHP?(如何在 PHP 中获取两个字符串之间的子字符串?)
问题描述
我需要一个函数来返回两个单词(或两个字符)之间的子字符串.我想知道是否有一个 php 函数可以实现这一点.我不想考虑正则表达式(好吧,我可以做一个,但真的不认为这是最好的方法).strpos
和 substr
函数的思考.下面是一个例子:
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 中获取两个字符串之间的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PHP 中获取两个字符串之间的子字符串?
基础教程推荐
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01