【问题标题】:Removing a character from a PHP string using Opencart使用 Opencart 从 PHP 字符串中删除一个字符
【发布时间】:2014-02-25 10:35:59
【问题描述】:

我目前正在使用 Opencart (1.5.6.1) 来运行多商店, 我有一家商店有很多产品,但它们都必须具有相同的名称, 现在在后端我有“Blah - Tshirt 15”“Blah - Tshirt 16”等等......

在 opencart 中有一个 foreach 循环

<?php foreach ($products as $product) { ?>
 <?php if ($product['name']) { ?>
  <?php if ($product['product_href']) { ?>
   <div class="name">
    <a href="<?php echo $product['product_href']; ?>">
     <?php echo $product['name']; ?>
    </a>
   </div>

<?php } else { ?>

<div class="name">
 <?php echo $product['name'];  ?>
</div>

<?php } ?>

<?php } ?>

现在这个页面上的输出,按照它所说的,输出产品名称“Blah - Tshirt 15” 或者他们叫什么。

但是,如果在客户看到的页面上我的客户希望每件 T 恤都只说

“废话-T恤”

有没有一种简单的方法可以让 str replacetrim 代码说,从 $product[name] 中删除最后 1 或 2 个字符

我不是PHP专家,我知道一点,但我想不通...

【问题讨论】:

  • 我认为最好的方法是在数据库 product_description 和产品表单中添加一个新字段,例如 - product_label。运行查询为现有产品插入值并将其显示在前端。

标签: php string replace opencart trim


【解决方案1】:

有一个名为 substr http://nl3.php.net/substr 的 PHP 函数。您可以使用substr($product['name'], 0, -1); 这将删除最后一个字符。如果您使用-2,它将删除最后两个字符,依此类推。

substr('yourstring'{string}, startindex{int}, endindex{int});

【讨论】:

  • 我选择使用 效果很好!!
【解决方案2】:

我会使用substr($product['name'], 0, -2) 来删除使用substr 的字符串的最后两个字符。

但是,如果要从字符串中删除所有数字,请使用正则表达式。喜欢preg_replace("/[0-9]/", "", $product['name']); 来自this SO post。它使用preg_replace

【讨论】:

    【解决方案3】:

    您可以按照其他人的建议使用 substr($var, 0, -n) 删除最后 n 个字符。但是,如果您想删除“字符串末尾的空格后跟任意数量的数字”,请改用正则表达式:preg_replace('/ \d+$/', '', $var)

    【讨论】:

      【解决方案4】:

      在您的模板中只需替换这一行

      <?php echo $product['name']; ?>
      

      用这条线

      <?php echo substr($product['name'], 0, strpos($product['name'], '- Tshirt') + 8); ?>
      

      这应该会导致这个结果:

      Blah - T 恤 1 -> Blah - T 恤
      Blah - T 恤 15 -> Blah - T 恤
      Blah - T 恤 150 -> Blah - T 恤

      没有尾随空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多