PHP子字符串提取.获取第一个'/'之前的字符串或整个字符串 [英] PHP substring extraction. Get the string before the first '/' or the whole string

查看:561
本文介绍了PHP子字符串提取.获取第一个'/'之前的字符串或整个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提取子字符串.在PHP中,我需要一些帮助.

I am trying to extract a substring. I need some help with doing it in PHP.

以下是一些我正在使用的示例字符串以及需要的结果:

Here are some sample strings I am working with and the results I need:

home/cat1/subcat2 => home

test/cat2 => test

startpage => startpage

我想获取直到第一个/的字符串,但是如果不存在/,请获取整个字符串.

I want to get the string till the first /, but if no / is present, get the whole string.

我尝试过

substr($mystring, 0, strpos($mystring, '/'))

我认为它说的是-获取/的位置,然后从位置0到那个位置获取子字符串.

I think it says - get the position of / and then get the substring from position 0 to that position.

我不知道如何处理没有/的情况,而又不会使语句太大.

I don't know how to handle the case where there is no /, without making the statement too big.

是否可以在不使PHP语句过于复杂的情况下处理这种情况?

Is there a way to handle that case also without making the PHP statement too complex?

推荐答案

使用 explode()

$arr = explode("/", $string, 2);
$first = $arr[0];

在这种情况下,我将limit参数用于explode,以便php扫描字符串的次数不会超过所需的数目.

In this case, I'm using the limit parameter to explode so that php won't scan the string any more than what's needed.

这篇关于PHP子字符串提取.获取第一个'/'之前的字符串或整个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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