我正在寻找正则表达式来确定一个字符串是否以另一个字符串开头。这必须是正则表达式,并且必须是 PHP 正则表达式。
$result = preg_match("#^startText(.*)$#i", $string);
if($result == 0)
{
echo "No match";
}
else
{
echo "Match found.";
}
preg_match
返回 0
(未找到匹配项)或 1
,因为 preg_match
在第一个匹配处停止。如果您想计算所有匹配项,请使用 preg_match_all
。
如果遇到更多问题,请检查 PHP 网站。
我不确定你为什么要使用正则表达式来查找字符串的子字符串?..但是你开始了...
/^(?=test).*$/
用法
<?php
// $result variable will be boolean (true|false)
$result = preg_match('/^(?=some_string).*$/', $search_string );
或者
<?php
function check(){
if(strpos('some_string', 'some_string_that is longer') == 0){ return true; } else { return false; }
}
正则表达式解释如下:
^ //anchor start matching to first letter
(?=.....) //look ahead - match exact string value
.* //match any leftover characters 0 to infinity x's
$ //anchor at end of string