Question

I need to check if $string1 is like $string2 but I dont want it to matter if one text is different than the otherif it starts with the same string. For example I would like

 if (admin.example2 == admin.example1) 

should return true! What's the best way to do this?

My exact requirement. An if condition to check if any string is starting with admin is present in the array.

 if ($client_name like 'admin') {
   ...
   ...
  }

There is unlimited number of entries in an array. I just want to check if any string is present which start with "admin" is there or not.

Was it helpful?

Solution 2

According to your new specified requirement, if a string starts with 'admin' can be checked like this:

$your_string = 'admin.test';
if(strcmp(substr($your_string, 0, 5), "admin") == 0) 
{
  echo 'begins with admin';
} else {
  echo 'does not begin with admin';
}

EDIT:

If you have an array of strings, example $array = array("admin.test", "test", "adminHello", "hello"), you could make a function that checks if the array contains at least one string that begins with admin:

function checkArrayStartsWithAdmin($array) 
{
  $result = false;
  foreach($array as $key => $value) 
  {
    if(strcmp(substr($value, 0, 5), "admin") == 0) 
    {
      $result = true;
      break;
    }
  }
  return $result;
}

OTHER TIPS

Seems like you are looking for similar_text in PHP

<?php
similar_text("admin.example2", "admin.example1", $simpercentage);
if($simpercentage>90)
{
    echo "Both strings are like ".round($simpercentage)."% similar.";
}

OUTPUT :

Both strings are like 93% similar.

Just set a percentage ratio (in the above case I have set it like 90% similarity) , You can adjust like as per your needs. The code will return 100% match if both strings are admin.example2 and admin.example2 (If both the strings are same)


As the question was edited drastically...

<?php
$arr=['admin1','administrator','admin2','I am an admin','adm','ADMIN'];
array_map(function ($v){ if(stripos(substr($v,0,5),'admin')!==false){ echo "$v starts with the text admin<br>";}},$arr);

OUTPUT :

admin1 starts with the text admin
administrator starts with the text admin
admin2 starts with the text admin
ADMIN starts with the text admin

You should probably want to take a look at the concept of the levenshtein distance.

You could use this php function.

http://www.php.net/manual/es/function.levenshtein.php

I hope it helps you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top