php 匹配函数

发布于 2025-01-07 04:24:56 字数 220 浏览 3 评论 0原文

我正在寻找执行此选项的函数:

preg_match("/^{$STRING}/i", ...)

但是,没有正则表达式,并且第一个中必须有 ^ ,这意味着该表达式将为 false:

$search = "hi", $search_in "ahi";

它必须位于细绳。

I am looking for function which does this option:

preg_match("/^{$STRING}/i", ...)

but, without regular expression, and there must be the ^ in the first, which means that this expression will be false:

$search = "hi", $search_in "ahi";

it must be at the start of the string.

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

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

发布评论

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

评论(5

停顿的约定 2025-01-14 04:24:56

不确定我是否很好地理解了您的请求...但是...尝试一下:

/** Checks if a target string (haystack) starts with a specified string (needle) */
function startsWith($haystack, $needle) {
    return (stripos($haystack, $needle) === 0);
}

/* Usage */
startsWith("ahi", "hi"); // Returns FALSE
startsWith("ahi", "ah"); // Returns TRUE

请注意,您需要使用 3 个 = 符号,因为当字符串中没有匹配项时该函数将返回 false。

http://php.net/manual/en/function.stripos.php< /a>


Not sure I understood your request well... But... Try this:

/** Checks if a target string (haystack) starts with a specified string (needle) */
function startsWith($haystack, $needle) {
    return (stripos($haystack, $needle) === 0);
}

/* Usage */
startsWith("ahi", "hi"); // Returns FALSE
startsWith("ahi", "ah"); // Returns TRUE

Please note that you need to use 3 = signs, because the function will return false when there is no match in the string.

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

且行且努力 2025-01-14 04:24:56
if(stripos($search_in, $search) === 0) {
  echo "matched";
}
if(stripos($search_in, $search) === 0) {
  echo "matched";
}
-黛色若梦 2025-01-14 04:24:56
stripos($haystack, $needle) === 0
stripos($haystack, $needle) === 0
深白境迁sunset 2025-01-14 04:24:56

用于此目的的精确函数是strncasecmp。我不知道为什么最近每个人都如此热衷于 stripos 解决方法。

尽管它需要字符串长度进行比较,并且结果必须对正匹配取反。

if (!strncasecmp($string, "search", 6)) {

优点是它实际上只比较前 6 个字符。它不会搜索整个主题,并且需要事后进行额外的比较。 (如果用作微优化,那就太愚蠢了。但它正是该任务的函数。)

The exact function for that purpose is strncasecmp. I have no idea why everyone is so bent on stripos workarounds recently.

Albeit it needs the string length for comparison, and the result must be negated for positive matches

if (!strncasecmp($string, "search", 6)) {

The advantage is that it really only compares the first 6 characters. It does not search the whole subject and require an extra comparison afterwards. (Stupid if used as microoptimization. But it's the exact function for that task.)

听,心雨的声音 2025-01-14 04:24:56
function startsWithi($haystack, $needle)
{
    return substr(strtolower($haystack), 0, strlen($needle))) === $needle;
}
function startsWithi($haystack, $needle)
{
    return substr(strtolower($haystack), 0, strlen($needle))) === $needle;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文