【问题标题】:Check if string equals, starts withs or ends with match检查字符串是否相等,以 r 开头以 match 结尾
【发布时间】:2012-12-31 02:17:42
【问题描述】:

我将如何改进此功能: 在数组中搜索以下任一字段名称:

  • a) 完全匹配
  • b) 用“_”检查字符串是否以
  • 开头
  • c) 以“_”结尾 检查字符串是否以

例如,我有一个列名列表:

array(
    'customer_name',
    'customer_lastname',
    'customer_streetname',
    'customer_dob',
    'system_modified'
)

还有一个带有格式化条件的数组:

array(
    '_dob' => 'date_dob',
    '_name' => 'varchar',
    'customer_name' => 'html_text',
    'system_' => 'required'
)

结果将条件应用于列名:

1. customer_name = html_text (exact matches have higher preference)
2. customer_lastname = varchar
3. customer_streetname = 
4. customer_dob = dob
5. system_modified = required

目前有这个:

protected function matchPatterns($string) {
    $return = array();
    $parrerns = $this->_normaliseArrayItem($this->getPatterns());
    foreach ($parrerns as $match) {

        // If exact match
        if($string == $match) {
            $return[] = $match;
            break;
        // Else if begins with _ and ends with string.
        } elseif($string[0] == "_" && substr_compare($string, $match, -strlen($match), strlen($match)) === 0) {
            $return[] = $match;
        }

    } // end loop
    return $return;
}


/**
 * Return an array of validation patterns.
 *
 * @return string[]
 */
public function getPatterns() {
    return $this->_patterns;
}


/**
 * Returns an item as array rather than single item.
 *
 * @param string[] $data
 * @return string[]
 */
protected function _normaliseArrayItem($data) {
    if(!isset($data[0])|| !is_array($data)) {
        $tmp[] = $data;
        $data = $tmp;
    }
    return $data;
}

【问题讨论】:

标签: php


【解决方案1】:
foreach ($parrerns as $match => $format) {
    // If exact match
    if($string == $match) {
        $return[] = $format;
        break;
    // Else if begins with _ and string ends with it.
    } elseif($match[0] == "_" && substr_compare($string, $match, -strlen($match), strlen($match)) === 0) {
        $return[] = $format;
    // Else if ends with _ and string begins with it
    } eleif (substr($match, -1) == "_" && substr_compare($string, $match, 0, strlen($match)) == 0) {
        $return[] = $format;
 }

【讨论】:

    【解决方案2】:

    改编自 Marc 的解决方案。

    if(substr($str, 0, 1) === '_' || substr($str, -1) === '_') {
        // it starts or ends with an underscore
    } else if($str == $match) {
        // it's the same
    }
    

    不过我不完全理解你的问题。

    【讨论】:

    • 正则表达式只是查看字符串的第一个字符是相当繁重的......为什么不substr($str,0,1) == '_'or $str[0] == '_'
    • 它们是,但对于简单的事情,它们的开销相当大。
    猜你喜欢
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2020-11-22
    • 2012-02-06
    • 2023-01-01
    • 1970-01-01
    • 2011-05-04
    相关资源
    最近更新 更多