【问题标题】:Search a PHP string for whitespace after a particular character在 PHP 字符串中搜索特定字符后的空格
【发布时间】:2015-11-26 21:10:48
【问题描述】:

这是我的字符串:

$string = '@ somebody and some other stuff';

如何检测@字符后的空格?

如果我找到匹配项,我想用原始字符串做点什么。

$string2 = '@ ';

【问题讨论】:

  • 不清楚你想要什么。你想检测你的字符串在某处是否有序列@ ?如果@ 后面没有空格,结果应该是什么?没有@ 应该是什么结果?如果字符串中有多个呢?
  • 我也想知道
  • 对不起,我认为它很清楚。我想检测字符串中的@是否后跟空格,然后将'@'分配给新变量
  • 如果没有呢?如果是多个? ...
  • 补充一点,我已经设置了逻辑来检测@符号之后的字符。但我遇到的问题是,如果有人写 '@ something',它会返回 'Array' 而不是 @ 符号。其余代码基于 @ 之后的字符创建数组。当有空白时,它显然无法正常工作。

标签: php string substring


【解决方案1】:

如果我理解正确,您想找到@ 并删除空格?

$string = str_replace("@ ", "@", $string);

编辑 你想要这个PHP source

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

【讨论】:

  • 不,我不想删除空格,我想保留它并将 @ 和它后面的空格分配给一个新变量
  • @Grant 这是你想要的,我刚刚添加了它。所以你可以检查它,如果它存在,用字符串做一些事情。祝你好运
  • 是的,这正是我所需要的。抱歉,如果我的问题不是更清楚,谢谢伙计;)
  • 欢迎您@Grant,如果您同意,请接受答案。祝你的项目好运。干杯
【解决方案2】:
$string = preg_replace('/@ (.*)/', '@ ', $string);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2012-07-23
    • 1970-01-01
    相关资源
    最近更新 更多