【问题标题】:Removing data in a string using wildcard [duplicate]使用通配符删除字符串中的数据[重复]
【发布时间】:2016-01-06 11:32:51
【问题描述】:

我正在尝试从字符串中删除所有数据,包括 "/"

$price="10/3"

我已经尝试过 preg_replace

$str = '2016/19';
$change = str_replace('/','-',$str);
$pattern = '/-*/';  
$new = preg_replace($pattern,'',$change);

我尝试按照上面的方式进行操作,因为不知道斜杠是否存在问题,所以我将字符串更改为 2016-19,然后尝试替换模式但它不会删除 -it 之后的数据删除 -

我也不能做 substr,因为 / 之前和之后的位数发生了变化

【问题讨论】:

  • 你需要转义/

标签: php string str-replace


【解决方案1】:

你几乎是对的。

$str = '2016/19';
// escape "/" by using "\/"
// .*$ matches any character up to the end of the string denoted by "$"
$pattern = '/\/.*$/';
$new = preg_replace($pattern,'',$str);

echo $new;

【讨论】:

  • 正则表达式需要用一个开始和匹配的结束字符括起来。大多数人使用“/”,就像上面的例子一样。确实可以使用许多字符,这也使其成为有效的正则表达式:“#/.*$#”。此处无需转义“/”。
  • 太棒了!知道这是我想念的简单的东西!
【解决方案2】:
$str = '2016/19';
$result = (explode("/", $str)[0]); //get the part before "/" after splitting

http://php.net/manual/en/function.explode.php

【讨论】:

    猜你喜欢
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2020-03-30
    • 1970-01-01
    相关资源
    最近更新 更多