我如何编写两个带字符串的函数,如果它以指定的字符/字符串开头或以它结尾,则返回?
例如:
$str = '|apples}';
echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
Run Code Online (Sandbox Code Playgroud) 我想用@ mywork.com限制我的电子邮件注册我在My_Form_validation中做了以下内容.
public function email_check($email)
{
$findme='mywork.com';
$pos = strpos($email,$findme);
if ($pos===FALSE)
{
$this->CI->form_validation->set_message('email_check', "The %s field does not have our email.");
return FALSE;
}
else
{
return TRUE;
}
}
Run Code Online (Sandbox Code Playgroud)
我用它如下.我对用户名和密码使用CI规则,它适用于电子邮件,它接受任何电子邮件地址.任何我感谢任何帮助.
function register_form($container)
{
....
....
/ Set Rules
$config = array(
...//for username
// for email
array(
'field'=>'email',
'label'=>$this->CI->lang->line('userlib_email'),
'rules'=>"trim|required|max_length[254]|valid_email|callback_email_check|callback_spare_email"
),
...// for password
);
$this->CI->form_validation->set_rules($config);
Run Code Online (Sandbox Code Playgroud) 解决方案:
strpos原来是效率最高的.可以完成,substr但会创建一个临时子字符串.也可以用正则表达式完成,但比strpos慢,如果单词包含元字符,并不总是产生正确的答案(参见Ayman Hourieh评论).
选择回答:
if(strlen($str) - strlen($key) == strrpos($str,$key))
print "$str ends in $key"; // prints Oh, hi O ends in O
Run Code Online (Sandbox Code Playgroud)
并且最好测试严格的平等===(参见David回答)
感谢所有人的帮助.
我正在尝试匹配字符串中的单词以查看它是否出现在该字符串的末尾.通常strpos($theString, $theWord);不会这样做.
基本上如果 $theWord = "my word";
$theString = "hello myword"; //match
$theString = "myword hello"; //not match
$theString = "hey myword hello"; //not match
Run Code Online (Sandbox Code Playgroud)
最有效的方法是什么?
PS在我所说的标题中strpos,但如果存在更好的方法,那也没关系.
我有一些数组,它们可能都是这样格式化的:
Array (
[0] => .
[1] => ..
[2] => 151108-some_image-006.jpg
[3] => high
[4] => low
)
Run Code Online (Sandbox Code Playgroud)
我知道他们有5个值,但我无法确定每个值的位置.
我试图从这个数组中只获取图像
$pos = array_search('*.jpg', $main_photo_directory);
echo $main_photo_directory[$pos];
Run Code Online (Sandbox Code Playgroud)
但是众所周知,它正在寻找一个*.jpg它无法找到的文字.我在正则表达式上并不那么优秀,也不知道如何格式化合适的字符串.
从这个数组中获取第一个图像(假设可能有多个图像)的最佳方法是什么?
加成
我要问的一个原因是找到一种搜索数组的简单方法.我不知道正则表达式,虽然我想使用它.我写了一个问题,寻找一个正则表达式,在字符串末尾找到'.jpg',没有搜索结果产生.