如何在PHP中使用开始和结束字符获取字符串的子字符串?

时间:2017-11-02 08:29:39

标签: php

我正在寻找使用 PHP 中的起始标记和结束标记来查找字符串的中间部分。

$str = 'Abc/hello@gmail.com/1267890(A-29)';
$agcodedup = substr($str, '(', -1);
$agcode = substr($agcodedup, 1);

agcode的最终预期值:

$agcode = 'A-29';

2 个答案:

答案 0 :(得分:4)

您可以使用preg_match

    $str = 'Abc/hello@gmail.com/1267890(A-29)';
    if(  preg_match('/\(([^)]+)\)/', $string, $match ) ) echo $match[1]."\n\n";

输出

   A-29

你可以在这里查看

http://sandbox.onlinephpfunctions.com/code/5b6aa0bf9725b62b87b94edbccc2df1d73450ee4

基本上正则表达式说:

  • 开始匹配,匹配\(打开Paren literal
  • 捕获论坛( .. )
  • 匹配除[^)]+以外的所有内容关闭Paren )
  • 结束比赛,匹配\)关闭Paren literal

哦,如果你真的把心放在substr上,你就去了:

$str = 'Abc/hello@gmail.com/1267890(A-29)';

//this is the location/index of the ( OPEN_PAREN
//strlen 0 based so we add +1 to offset it
$start = strpos( $str,'(') +1;
//this is the location/index of the ) CLOSE_PAREN.
$end = strpos( $str,')');
//we need the length of the substring for the third argument, not its index
$len = ($end-$start);  

echo substr($str, $start, $len );

OUPUTS

A-29

你可以在这里测试一下

http://sandbox.onlinephpfunctions.com/code/88723be11fc82d88316d32a522030b149a4788aa

如果是我,我会对两种方法进行基准测试,看看哪种方法更快。

答案 1 :(得分:0)

这对你有帮助。

function getStringBetween($str, $from, $to, $withFromAndTo = false)
{
    $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));

    if ($withFromAndTo) {
        return $from . substr($sub,0, strrpos($sub,$to)) . $to;
    } else {
        return substr($sub,0, strrpos($sub,$to));
    }

    $inputString = "Abc/hello@gmail.com/1267890(A-29)";
    $outputString = getStringBetween($inputString, '(', ')');

    echo $outputString; 
    //output will be A-29

    $outputString = getStringBetween($inputString, '(', ')', true);
    echo $outputString; 
    //output will be (A-29)


    return $outputString;
}