Search For Characters in a String - php

$str1 = "HEADINGLEY";
$str2 = "HDNGLY";
how can i seach string 1 to see if it contains all the characters from string 2 in the order they exist in string 2 and return a true or false value ?
Any help appreciated :D
if this helps, this is the code i have todate..
echo preg_match('/.*H.*D.*N.*G.*L.*Y.*/', $str1, $matches);
returns 0

I guess I'd use preg_match
http://us.php.net/manual/en/function.preg-match.php
...and turning $str2 into a regular expression using str_split to get an array and implode to turn it back into a string with ".*" as glue between characters.
http://us.php.net/manual/en/function.str-split.php
http://us.php.net/manual/en/function.implode.php
Upate -- I should have suggested str_split instead of explode, and here is the code that will get you a regular expression from $str2
$str2pat = "/.*" . implode(".*", str_split($str2)) . ".*/";

You could use some regular expression match like .*H.*D.*N.*G.*L.*Y.* and preg_match.
Should be easy enough to add the .* in the second string.

This code is in C# as I don't know PHP but should be easy to understand.
int index1 = 0, index2 = 0;
while (index1 < str1.Length && index2 < str2.Length)
{
if (str1[index1] == str2[index2]) index2++;
index1++;
}
if (index2 == str2.Length) return true;

Imagine that your string is array and after that use array_diff function.
http://hu2.php.net/array_diff
$str1 = "HEADINGLEY";
$str2 = "HDNGLY";
$arr1 = str_split($str1, 1);
$arr2 = str_split($str2, 1);
$arr2_uniques = array_diff($arr2, $arr1);
return array() === $arr2_uniques;

Possibly this snippet will do it:
var contains = true;
for (var i=0; i < str2.length; i++)
{
var char = str2.charAt(i);
var indexOfChar = str1.indexOf(char);
if (indexOfChar < 0)
{
contains = false;
}
str1 = str1.substr(indexOfChar);
}

You can use pre_match function, like that:
$split_str2 = str_split($str2);
// Create pattern from str2
$pattern = "/" . implode(".*", $split_str2) . "/";
// Find
$result = preg_match($pattern, $str1);

You can probably use some regular expression but be weary of strings that contained regex specific characters. This solution does it programmatically.
function contains_all_characters($str1, $str2)
{
$i1 = strlen($str1) - 1;
$i2 = strlen($str2) - 1;
while ($i2 >= 0)
{
if ($i1 == -1) return false;
if ($str1[$i1--] == $str2[$i2]) $i2--;
}
return true;
}

You can try:
$str = 'HEADINGLEY';
if (preg_match('/[^H]*H[^D]*D[^N]*N[^G]*G[^L]*L[^Y]*Y/', $str, $m))
var_dump($m[0]);
Update: Even better is to build regex like this and then use it:
$str = 'HEADINGLEY';
$pattern = 'HDNGLY';
$regex = '#' . preg_replace('#(.)#', '[^$1]*$1', $pattern) . '#';
if (preg_match($regex, $str, $m))
var_dump($m[0]);
OUTPUT:
string(10) "HEADINGLEY"

Related

How to trim string from right in PHP?

I have a string example
this-is-the-example/exa
I want to trim /exa from the above line
$string1 = "this-is-the-example/exa";
$string2 = "/exa";
I am using rtrim($string1, $sting2)
But the output is this-is-the-exampl
I want to this-is-the-example as output.
Both string are dynamic and may have multiple occurrences within the string. But I only want to remove the last part. Also its not compulsory that the string2 has / in it. this may be normal string too. like a, abc too..
There are various approaches you can use for this:
With substr(DEMO):
function removeFromEnd($haystack, $needle)
{
$length = strlen($needle);
if(substr($haystack, -$length) === $needle)
{
$haystack = substr($haystack, 0, -$length);
}
return $haystack;
}
$trim = '/exa';
$str = 'this-is-the-example/exa';
var_dump(removeFromEnd($str, $trim));
With regex(DEMO):
$trim = '/exa';
$str = 'this-is-the-example/exa';
function removeFromEnd($haystack, $needle)
{
$needle = preg_quote($needle, '/');
$haystack = preg_replace("/$needle$/", '', $haystack);
return $haystack;
}
var_dump(removeFromEnd($str, $trim));
First explode the string, remove last element from exploded array using array_pop, then implode it back again with /.
$str = "this-is-the-example/exa";
if(strpos($str, '/') !== false)
{
$arr = explode('/', $str);
array_pop($arr);
$str = implode('/', $arr);
// output this-is-the-example
}
This will work event if you have multiple / in the URL and will remove last element only.
$str = "this-is-the-example/somevalue/exa";
if(strpos($str, '/') !== false)
{
$arr = explode('/', $str);
array_pop($arr);
$str = implode('/', $arr);
// output this-is-the-example
}
Say hi to strstr()
$str = 'this-is-the-example/exa';
$trim = '/exa';
$result = strstr($str, $trim, true);
echo $result;
You can use explode
<?php
$x = "this-is-the-example/exa";
$y = explode('/', $x);
echo $y[0];
the second parameter of rtrim is a character mask and not a string, your last "e" is trimed and that's normal.
COnsider using something else, regexp for example (preg_replace) to fit your needs
This keeps everything before "/" char :
$str = preg_replace('/^([^\/]*).*/','$1', 'this-is-the-example/exa');
This removes the last part.
$str = preg_replace('/^(.*)\/.*$/','$1', 'this-is-the-example/exa/mple');
Hope this helps. :)
Simply try this code:
<?php
$this_example = substr("this-is-the-example/exa", 0, -4);
echo "<br/>".$this_example; // returns "this-is-the-example"
?>
To allow for error handling, if the substring is not found in the search string ...
<?php
$myString = 'this-is-the-example/exa';
//[Edit: see comment below] use strrpos, not strpos, to find the LAST occurrence
$endPosition = strrpos($myString, '/exa');
// TodO; if endPosition === False then handle error, substring not found
$leftPart = substr($myString, 0, $endPosition);
echo($leftPart);
?>
outputs
this-is-the-example

php extract a sub-string before and after a character from a string

need to extract an info from a string which strats at 'type-' and ends at '-id'
IDlocationTagID-type-area-id-492
here is the string, so I need to extract values : area and 492 from the string :
After 'type-' and before '-id' and after 'id-'
You can use the preg_match:
For example:
preg_match("/type-(.\w+)-id-(.\d+)/", $input_line, $output_array);
To check, you may need the service:
http://www.phpliveregex.com/
P.S. If the function preg_match will be too heavy, there is an alternative solution:
$str = 'IDlocationTagID-type-area-id-492';
$itr = new ArrayIterator(explode('-', $str));
foreach($itr as $key => $value) {
if($value === 'type') {
$itr->next();
var_dump($itr->current());
}
if($value === 'id') {
$itr->next();
var_dump($itr->current());
}
}
This is what you want using two explode.
$str = 'IDlocationTagID-type-area-id-492';
echo explode("-id", explode("type-", $str)[1])[0]; //area
echo trim(explode("-id", explode("type-", $str)[1])[1], '-'); //492
Little Simple ways.
echo explode("type-", explode("-id-", $str)[0])[1]; // area
echo explode("-id-", $str)[1]; // 492
Using Regular Expression:
preg_match("/type-(.*)-id-(.*)/", $str, $output_array);
print_r($output_array);
echo $area = $output_array[1]; // area
echo $fnt = $output_array[2]; // 492
You can use explode to get the values:
$a = "IDlocationTagID-type-area-id-492";
$data = explode("-",$a);
echo "Area ".$data[2]." Id ".$data[4];
$matches = null;
$returnValue = preg_match('/type-(.*?)-id/', $yourString, $matches);
echo($matches[1]);

How to find out if there is any redundant word in string in php?

I need to find out if there are any redundant words in string or not .Is there any function that can provide me result in true/false.
Example:
$str = "Hey! How are you";
$result = redundant($str);
echo $result ; //result should be 0 or false
But for :
$str = "Hey! How are are you";
$result = redundant($str);
echo $result ; //result should be 1 or true
Thank you
You could use explode to generate an array containing all words in your string:
$array = explode(" ", $str);
Than you could prove if the arrays contains duplicates with the function provided in this answer:
https://stackoverflow.com/a/3145660/5420511
I think this is what you are trying to do, this splits on punctuation marks or whitespaces. The commented out lines can be used if you want the duplicated words:
$str = "Hey! How are are you?";
$output = redundant($str);
echo $output;
function redundant($string){
$words = preg_split('/[[:punct:]\s]+/', $string);
if(max(array_count_values($words)) > 1) {
return 1;
} else {
return 0;
}
//foreach(array_count_values($words) as $word => $count) {
// if($count > 1) {
// echo '"' . $word . '" is in the string more than once';
// }
//}
}
References:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php
Regex Demo: https://regex101.com/r/iH0eA6/1

Explode on unescaped white space only in PHP

I would like to explode this kind of string in PHP:
$foo = "foo.txt da\ code.txt bar.txt";
And I want to explode it to have:
["foo.txt", "da\ code.txt", "bar.txt"]
I know I can use preg_split but I don't see what to put as regular expression.
Could someone help me?
You could match on a positive look behind for any space preceded by alpha characters.
<?php
$foo = "foo.txt da\ code.txt bar.txt";
print_r(preg_split("/(?<=[a-zA-Z])\s/", $foo));
You could also use a negative lookbehind for the general case
<?php
$foo = "foo.txt da\ code.txt bar.txt something.mp3 other# 9asdf";
print_r(preg_split('/(?<!\\\\)\s/', $foo));
Here's a funky, non-regex "parser". All kinds of fun. What was the world like before regular expressions? I mean, it must have been work. ;)
<?php
$foo = "foo.txt da\ code.txt bar.txt";
$foos = array();
$char = 0;
$index = 0;
$lookback = '';
while ($char < strlen($foo)) {
$lookback = $foo{$char-4} . $foo{$char-3} . $foo{$char-2} . $foo{$char-1} . $foo{$char};
if ($lookback == '.txt ') $index++;
$foos[$index] .= $foo{$char++};
}
print_r(array_map('trim', $foos));
?>
http://codepad.org/XMfLemeg
You could use preg_split() but it is slow so if escaped space is your only problem a lot faster would be to do it as simply as:
$array1 = explode(' ', $list);
$array2 = [];
$appendNext = false;
foreach($array1 as $elem)
{
if ($appendNext)
{
array_push($array2, array_pop($array2) . ' ' . $elem);
}
else
{
$array2[] = $elem;
}
$appendNext = (substr($elem, -1) === '\\');
}
var_dump($array2);
If you really want to do it via regex here is a working solution:
print_r(preg_split("/(?<!\\\)\s/", $foo));
http://codepad.org/ngbDaxA3
but it will be slower than above

Php search string (with wildcards)

Is there a way to put a wildcard in a string? The reason why I am asking is because currently I have a function to search for a substring between two substrings (i.e grab the contents between "my" and "has fleas" in the sentence "my dog has fleas", resulting in "dog").
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
What I want to do is have it search with a wildcard in the string. So say I search between "%WILDCARD%" and "has fleas" in the sentence "My dog has fleas" - it would still output "dog".
I don't know if I explained it too well but hopefully someone will understand me :P. Thank you very much for reading!
This is one of the few cases where regular expressions are actually helpful. :)
if (preg_match('/my (\w+) has/', $str, $matches)) {
echo $matches[1];
}
See the documentation for preg_match.
wildcard pattern could be converted to regex pattern like this
function wildcard_match($pattern, $subject) {
$pattern = strtr($pattern, array(
'*' => '.*?', // 0 or more (lazy) - asterisk (*)
'?' => '.', // 1 character - question mark (?)
));
return preg_match("/$pattern/", $subject);
}
if string contents special characters, e.g. \.+*?^$|{}/'#, they should be \-escaped
don't tested:
function wildcard_match($pattern, $subject) {
// quotemeta function has most similar behavior,
// it escapes \.+*?^$[](), but doesn't escape |{}/'#
// we don't include * and ?
$special_chars = "\.+^$[]()|{}/'#";
$special_chars = str_split($special_chars);
$escape = array();
foreach ($special_chars as $char) $escape[$char] = "\\$char";
$pattern = strtr($pattern, $escape);
$pattern = strtr($pattern, array(
'*' => '.*?', // 0 or more (lazy) - asterisk (*)
'?' => '.', // 1 character - question mark (?)
));
return preg_match("/$pattern/", $subject);
}
Use a regex.
$string = "My dog has fleas";
if (preg_match("/\S+ (\S+) has fleas/", $string, $matches))
echo ($matches[1]);
else
echo ("Not found");
\S means any non-space character, + means one or more of the previous thing, so \S+ means match one or more non-space characters. (…) means capture the content of the submatch and put into the $matches array.
I agree that regex are much more flexible than wildcards, but sometimes all you want is a simple way to define patterns. For people looking for a portable solution (not *NIX only) here is my implementation of the function:
function wild_compare($wild, $string) {
$wild_i = 0;
$string_i = 0;
$wild_len = strlen($wild);
$string_len = strlen($string);
while ($string_i < $string_len && $wild[$wild_i] != '*') {
if (($wild[$wild_i] != $string[$string_i]) && ($wild[$wild_i] != '?')) {
return 0;
}
$wild_i++;
$string_i++;
}
$mp = 0;
$cp = 0;
while ($string_i < $string_len) {
if ($wild[$wild_i] == '*') {
if (++$wild_i == $wild_len) {
return 1;
}
$mp = $wild_i;
$cp = $string_i + 1;
}
else
if (($wild[$wild_i] == $string[$string_i]) || ($wild[$wild_i] == '?')) {
$wild_i++;
$string_i++;
}
else {
$wild_i = $mp;
$string_i = $cp++;
}
}
while ($wild[$wild_i] == '*') {
$wild_i++;
}
return $wild_i == $wild_len ? 1 : 0;
}
Naturally the PHP implementation is slower than fnmatch(), but it would work on any platform.
It can be used like this:
if (wild_compare('regex are * useful', 'regex are always useful') == 1) {
echo "I'm glad we agree on this";
}
If you insist to use a wildcard (and yes, PREG is much better) you can use the function
fnmatch.
ex:
if (fnmatch('my * has', $str)) { }

Categories