php 如何通过PHP从字符串中获取子字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5752594/
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:22:46  来源:igfitidea点击:

How to get a substring from string through PHP?

php

提问by Abhi

Hi want to change the displayed username like [email protected] to only abcd. so for this i should clip the part starting from @.

嗨,想将显示的用户名(如 [email protected])更改为仅 abcd。所以为此我应该剪辑从@开始的部分。

I can do this very easily through variablename.substring() function in Java or C# , but I m not aware with the syntax of PHP. So help me do that .

我可以通过 Java 或 C# 中的 variablename.substring() 函数很容易地做到这一点,但我不知道 PHP 的语法。所以帮我做那个。

Suppose i m having variable like .

假设我有像 .

$username = "[email protected]";
$username = some

string manipultion functiona should get called here ; so that echo $username; can results in abcd only.

应该在这里调用字符串操作函数;这样 echo $username; 只能产生 abcd。

回答by Sander Marechal

Try this:

尝试这个:

$username = substr($username, 0, strpos($username, '@'));

回答by MD Sayem Ahmed

Use strstrfunction.

使用strstr函数。

An example from the PHP reference -

PHP参考中的一个例子 -

<?php
    $email  = '[email protected]';
    $domain = strstr($email, '@');
    echo $domain; // prints @example.com

    $user = strstr($email, '@', true); // As of PHP 5.3.0
    echo $user; // prints name
?>

回答by Wes

list($username, $domain) = explode('@', '[email protected]')

回答by alex

Use strtok().

使用strtok().

$username = strtok($email, '@');

CodePad.

键盘

回答by Ibu

substr(string, 0, 20)

String, start, length

字符串,开始,长度