PHP:替换数组中不存在的所有单词

发布于 2024-12-11 19:05:47 字数 381 浏览 0 评论 0原文

我正在尝试使用 PHP 解析用户输入的字符串日期。我需要删除除这两个可接受的类别之外的所有字符:

1) [0-9,\./-] (numerals, comma, period, slash, and dash)
2) An array of acceptable words:
    $monthNames=array(
        "january"=>1,
        "jan"=>1,
        "february"=>2,
        "feb"=>2
    );

我尝试对字符单词边界进行explode()ing,然后删除不在数组中的每个部分,但这导致了相当混乱。有没有一种优雅的方法来实现这一点?

谢谢!

I am trying to parse user-entered string dates with PHP. I need to remove all characters other than these two acceptable categories:

1) [0-9,\./-] (numerals, comma, period, slash, and dash)
2) An array of acceptable words:
    $monthNames=array(
        "january"=>1,
        "jan"=>1,
        "february"=>2,
        "feb"=>2
    );

I tried explode()ing on character word bounaries and then removing each section that is not in the array, but that led to quite a mess. Is there an elegant way of accomplishing this?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

再见回来 2024-12-18 19:05:47

您可以使用 strtotime()

echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";

检查是否失败:

$str = 'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}

请参阅 http: //php.net/manual/en/function.strtotime.php

另外,DateTime::createFromFormat() 可能会有用。

请参阅http://www.php.net/manual/en/datetime.createfromformat。 php

You could use strtotime()

echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";

To check for failure:

$str = 'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}

See http://php.net/manual/en/function.strtotime.php

Also DateTime::createFromFormat() might be useful.

See http://www.php.net/manual/en/datetime.createfromformat.php

十年不长 2024-12-18 19:05:47

避免这种情况的最佳方法是将日期条目设置为仅包含有效选项的表单,并丢弃其余选项。

Best way to avoid that would be to make the date entry a form with only valid option and discard the rest.

不寐倦长更 2024-12-18 19:05:47

您可以使用正则表达式来匹配日期,这是一个非常简单、基本的表达式:

preg_match('/((Jan|Feb|Dec|\d{1,2})[ .\/-]){2,2}\d{1,4}/i', $str, $matches);
echo $matches[0];

不过,您必须添加其他月份。

不眠之夜的进一步想法:

  • 禁止月份<< 1和> 12
  • 不允许 Jan Jan 2011
  • 不允许奇怪的年份
  • ...
  • 废弃它并找到一个好的年份;)

我会采取两步方法:

  1. 提取看起来日期的东西
  2. 使用内置时间函数检查是否可以构建一个时间戳这是有道理的。如果做不到,就扔掉它。

You could use a regulare expression to match dates, here's a very simplistic, rudimentary one:

preg_match('/((Jan|Feb|Dec|\d{1,2})[ .\/-]){2,2}\d{1,4}/i', $str, $matches);
echo $matches[0];

You'll have to add the other months, though.

Further ideas for sleepless nights:

  • disallow months < 1 and > 12
  • disallow Jan Jan 2011
  • disallow strange years
  • ...
  • scrap it and find a good one ;)

I'd take a two step approach:

  1. Extract something that looks date
  2. Use the built-in time functions to check if one can build a timestamp that makes sense from it. If one can't, throw it out.
秋凉 2024-12-18 19:05:47

如果可以安全地假设您的 $monthNames 数组少于 26 个元素,那么以下方法有效(尽管这绝对是一个“黑客” - 如果我能想到一些东西,我会提供另一个答案值得被称为“优雅”):

<?php

$text = 'january 3 february 7 xyz';
print 'original string=[' . $text . "]\n";

$monthNames = array(
    'january' => 1,
    'jan' => 1,
    'february' => 2,
    'feb' => 2
    // ... presumably there are some more array elements here...
);

// Map each monthNames key to a capital letter:
$i = 65; // ASCII code for 'A'
$mmap = array();
foreach (array_keys($monthNames) as $m) {
    $c = chr($i);
    $mmap[$c] = $m;
    $i += 1;
}

// Strip out capital letters first:
$text1 = preg_replace('/[A-Z]+/', "", $text);

// Replace each month name with its letter:
$text2 = str_replace(array_keys($monthNames), array_keys($mmap), $text1);

// Filter out everything that is not allowed:
$text3 = preg_replace('/[^0-9,\.\-A-Z]/', "", $text2);

// Restore the original month names:
$text4 = str_replace(array_keys($mmap), array_keys($monthNames), $text3);

print 'filtered string=[' . $text4 . "]\n"; 
?>

注意:

  1. 如果您要从过滤中排除超过 26 个字符串,那么您可以编写代码来利用相同的想法,但在我看来,这变得相当困难使上述代码能够被人类(或者至少是我)理解。
  2. 当然,如果您决定确实需要空格,您当然可以调整 preg_replace() 模式以保留空格。

If it is safe to assume that your $monthNames array has less than 26 elements, then the following works (though this is definitely a "hack" - I'll offer another answer if I can think of something which deserves to be called "elegant"):

<?php

$text = 'january 3 february 7 xyz';
print 'original string=[' . $text . "]\n";

$monthNames = array(
    'january' => 1,
    'jan' => 1,
    'february' => 2,
    'feb' => 2
    // ... presumably there are some more array elements here...
);

// Map each monthNames key to a capital letter:
$i = 65; // ASCII code for 'A'
$mmap = array();
foreach (array_keys($monthNames) as $m) {
    $c = chr($i);
    $mmap[$c] = $m;
    $i += 1;
}

// Strip out capital letters first:
$text1 = preg_replace('/[A-Z]+/', "", $text);

// Replace each month name with its letter:
$text2 = str_replace(array_keys($monthNames), array_keys($mmap), $text1);

// Filter out everything that is not allowed:
$text3 = preg_replace('/[^0-9,\.\-A-Z]/', "", $text2);

// Restore the original month names:
$text4 = str_replace(array_keys($mmap), array_keys($monthNames), $text3);

print 'filtered string=[' . $text4 . "]\n"; 
?>

NOTES:

  1. If you've got more than 26 strings to exclude from filtering, then you can write code to exploit the same idea, but IMO it gets considerably harder to make said code understandable by humans (or by me, at any rate).
  2. You can of course adjust the preg_replace() pattern to leave whitespaces alone if you decide that you really do want them after all.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文