1

I have an array of characters -

$operators = array('%', '*', '+', '-', '@');

and a string for eg-

$text = '%@';

How can I find if the string contains two values from the array in concatenation -

Like $text = %test% - valid, but $text = %+test should fail ($concat = TRUE).

This is what I've tried -

$concat = FALSE;
foreach ($operators as $op) {
  $opPosition[$op] = strpos($text, $op);
  // Here I need to check if any two values of
  // $opPosition are neighbours, set the $concat variable to TRUE.
}

How do I make a check for $opPosition or is this the only way what I'm trying ?

8
  • Dig a little into regular expressions. I think that this would be helpful: preg_match_all() Commented Dec 14, 2016 at 6:39
  • 1
    try preg_match("/[%\*\+\-@]{2,}/", $text); Commented Dec 14, 2016 at 6:45
  • @bansi As I have a whole array to check from, thought the regex would a long string to configure Commented Dec 14, 2016 at 6:49
  • Well the above regex seems to be handling most of the cases Commented Dec 14, 2016 at 6:51
  • @bansi Wouldn't your regex fail for %+test? Commented Dec 14, 2016 at 6:54

2 Answers 2

1

You can use preg_match like below.

// $concat will be 1 for any match
$concat = preg_match("/[%\*\+\-@]{2,}/", $text);

You can find the explanation for the regular expression here

Note: $concat will be 0 even if some error occurs. You may need to use == operator.

Edit: if your operators are in and array, or need flexibility to add, change or remove operators without disturbing the regular expression you can use the following code.

$text = "test%+";
$operators = array('%', '*', '+', '-', '@');
// create regular expression by imploding the array to string and using
// preg_quote to Quote regular expression characters
$expression = preg_quote(implode('', $operators), '/');
$concat = preg_match("/[$expression]{2,}/", $text);

Reference for preg_quote

Demo here

Sign up to request clarification or add additional context in comments.

Comments

0

Try to Use this code section to get your desired output -

$operators = array('%', '*', '+', '-', '@');
$text = '%test%';
$end = substr($text,-1);
$start = substr($text, 0,1);
if(($start == $end) && in_array($start, $operators) == 1){
  echo "valid";
}else{
  echo "Not Valid";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.