(Sorry! Revision regarding the $ character. Explaining via example as well)
I need to run a test on two string variable开发者_JAVA百科s:
$a, $b
If $a is contained in $b, I need to see if their "difference" ($b-$a) contains the $ character in it. If it does, then return the "difference", else in all other cases, the test should return FALSE
Also $a should only occur at the END of $b...
$b = "abcde" $a = "cde" should result in true (no $ detected)
$b = "zyw$abcde" $a = "cde" should result in false ($ detected)
$b = "cdeab" $a = "cde" should result in false (NOT at the end)
$b = "zxwq" $a = "cde" should result in false ($a doesnt exist in $b)
HTH!
- Use
strpos
to determine the position of $a in $b - Use
substr
to get the parts from $b which do not contain $a - Use
strpos
to check whether those parts contain $.
$ret = false;
if (strpos($b, $a) !== false) {
$ret = (substr_count($b) > substr_count($a));
}
$ret is your answer
Edit: updated after question edit
This should work:
<?php
function string_func_thing($a, $b) {
$count = 0;
//get $b with $a removed
$result = str_ireplace($a, '', $b, $count);
//if $a was not in $b
if (!$count) {
return false;
}
//if whatever is left contains $
if (false !== strpos($result, '$')) {
return false;
}
return true;
}
var_dump( string_func_thing('ter', 'computer$') ); //bool(false)
var_dump( string_func_thing('ter', 'computer') ); //bool(true)
var_dump( string_func_thing('hello', 'computer') ); //bool(true)
$a = 'cde';
$regex = '/^[^$]*' . $a . '$/m';
if (preg_match($regex, $b)) {
# Successful match
} else {
# Match attempt failed
}
精彩评论