donglun1918 2016-02-18 11:11
浏览 43
已采纳

检查一个字符串是否以“开头并以”结束,如果不是则添加到字符串中

I need to check if a string starts and ends with the ". And if it is not the case, the " should be added to it. e.g. text convert into "text". I'm using the folling code for this:

if (strpos($owner_text, '"') !== 0)
{
    $owner_text = '"' . $owner_text . '"';
}

then I realized, this will not work if I have something like text" or "text. In these cases, text" will be converted into "text"" and "text will stay untouched. So I change the code above:

// e.g. text. strpos returns false if nothing found
if (strpos($owner_text, '"') === false && strrpos($owner_text, '"') === false)
{
    $owner_text = '"' . $owner_text . '"';
}
// "text
else if (strpos($owner_text, '"') === 0 && strrpos($owner_text, '"') === 0)
{
    $owner_text = $owner_text . '"';
}

else if (strpos($owner_text, '"') !== 0 && strrpos($owner_text, '"') !== 0)
{
    // text"
    if (strpos($owner_text, '"') == strlen($owner_text) - 1)
    {
        $owner_text = '"' . $owner_text;
    }
    // te"xt
    else
    {
        $owner_text = '"' . $owner_text . '"';
    }
}

this works now with text "text or text", but it seems reaaaally complicated and it has problem with something like te"xt". How should I do this properly?

  • 写回答

2条回答 默认 最新

  • duan97689 2016-02-18 11:18
    关注

    Just check first and last character instead of searching for " in the whole string:

    if ($owner_text[0] != '"') $owner_text = '"'.$owner_text;
    if ($owner_text[strlen($owner_text)-1] != '"') $owner_text = $owner_text.'"';
    

    Note that this code does not do any error checking on $owner_text.

    Update You can even do it with less code (and this also takes care of error handling, e.g. if $onwer_text is empty):

    $owner_text = '"'.trim($owner_text, '"'), '"';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题