【问题标题】:get 11 characters in a string following a prefix [closed]在前缀后面的字符串中获取 11 个字符 [关闭]
【发布时间】:2017-12-27 08:54:30
【问题描述】:

我想这样做

$name = "hello word XYZabcdefghijklmnopqrstuvwxyz bluesky";

输出应如下所示: "abcdefghijk"

11 个字符。

请注意:XYZ是前缀

【问题讨论】:

标签: php


【解决方案1】:

substr() 方法就是你要找的:

string substr (string $string , int $start [, int $length ] )

返回由 start 和 length 参数指定的字符串部分。

首先你在 $name 中找到 $prefix 的位置:

strpos($name, $prefix)

然后您需要添加前缀的长度以移动到正确的位置,并传递您希望在结果中获得的字符数(在您的情况下为 11):

$name = "hello word XYZabcdefghijklmnopqrstuvwxyz bluesky";
$prefix = "XYZ";

$output = substr($name, strpos($name, $prefix) + strlen($prefix), 11);
echo $output;

【讨论】:

  • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
  • 你是对的。我编辑了解决方案。
【解决方案2】:

试试这个

<?php

$name = "hello word XYZabcdefghijklmnopqrstuvwxyz bluesky";

$out = substr(substr($name, strpos($name, 'XYZ'), 14), 3);

echo $out;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 2016-08-03
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    相关资源
    最近更新 更多