【问题标题】:custom substr php自定义 substr php
【发布时间】:2012-08-28 17:39:17
【问题描述】:

使用以下字符串:

$string='some text <photo id="id#" /> some text';

创建一个 substr,如果它的字符串的结尾是

的一部分
<photo id="id#" />

然后应用一个额外的块来完成

"<photo id="id#" />"

例子:

substr($string,0,15);

结果是:

some text <phot

如果发生这种情况,我最终需要:

some text <photo id="id#" />

他,找不到这样做的方法。顺便说一下 id# 是一个随机数值,其长度不会超过 3 个字符。如果需要正则表达式来提供功能。

【问题讨论】:

标签: php regex substring


【解决方案1】:

看到这个:-

输出:-

<?php

$str= 'some text <photo id="#xx"/> some test';
$parts = preg_split('~(</?[\w][^>]*>)~', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo '<pre>';
print_r($parts);
echo htmlentities($parts[1]);


$str_new= 'some text <photo id="#xx"></photo> some test';
$parts_new = preg_split('~(</?[\w][^>]*>)~', $str_new, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo '<pre>';
print_r($parts_new);
echo htmlentities($parts_new[1]);
echo htmlentities($parts_new[2]);

?>

【讨论】:

    【解决方案2】:

    无需使用正则表达式,只需使用 PHP 字符串函数即可:

    $string = 'some text <photo id="id#" /> some text';
    $newString = substr($string, 0, strpos($string, '>') + 1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多