How can I efficiently determine if a given string contains two strings?
For example, let's say I'm given the string: abc-def-jk-l. This string either contains two strings divided by a -, or it's not a match. The matching possibilities are:
Possible Matches for "abc-def-jk-l" :
abc def-jk-l
abc-def jk-l
abc-def-jk l
Now, here are my columns of strings to match:
Column I Column II
------- -------
1. abc-def A. qwe-rt
2. ghijkl B. yui-op
3. mn-op-qr C. as-df-gh
4. stuvw D. jk-l
How can I efficiently check to see if the given string matches two strings in the columns above? (The above is a match - matching abc-def and jk-l)
Here are some more examples:
abc-def-yui-op [MATCH - Matches 1-B]
abc-def-zxc-v [NO MATCH - Matches 1, but not any in column II.]
stuvw-jk-l [MATCH - Matches 4-D]
mn-op-qr-jk-l [Is this a match?]
Now, given a strings above, how can I efficiently determine matches? (Efficiency will be key, because columns i and ii will each have millions of rows on indexed columns in their respected tables!)
UPDATE: The order will always be column i, then column ii. (or "no match", which could mean it matches only one column or none)
Here's some php to help:
<?php
$arrStrings = array('abc-def-yui-op','abc-def-zxc-v','stuvw-jk-l','stuvw-jk-l');
foreach($arrStrings as $string) {
print_r(stringMatchCheck($string));
}
function stringMatchCheck($string) {
$arrI = array('abc-def','ghijkl','mn-op-qr','stuvw');
$arrII = array('qwe-rt','yui-op','as-df-gh','jk-l');
// magic stackoverflow help goes here!
if ()
return array($match[0],$match[1]);
else
return false;
}
?>
Just use PHP's strpos(). Loop until you find an entry from $arrI in $string using strpos(), and do the same for $arrII.
More info on strpos(): http://php.net/manual/en/function.strpos.php
EDIT:
To help you see what I'm talking about, here's your function:
function stringMatchCheck($string) {
$arrI = array('abc-def','ghijkl','mn-op-qr','stuvw');
$arrII = array('qwe-rt','yui-op','as-df-gh','jk-l');
$match = array(NULL, NULL);
// get match, if any, from first group
for ($i=0; $i<count($arrI) && !is_null($match[0]); $i++) {
if (strpos($string,$arrI[$i]) !== false) {
$match[0]=$arrI[$i];
}
}
if (!is_null($match[0])) {
// get match, if any, from second group group
for ($i=0; $i<count($arrII) && !is_null($match[1]); $i++) {
if (strpos($string,$arrII[$i]) !== false) {
$match[1]=$arrII[$i];
}
}
}
if (!is_null($match[0]) && !is_null($match[1])) {
return $match;
} else {
return false;
}
}
For efficiency sake, rather than loop through every entry in each column, split the string into as many different words as it takes and search for every word combination. Basically what you mention as possible matches.
$words = explode("-", $string);
$end = count($words) - 1;
for ( $i = 1; $i < $end; $i++ ) {
$partOne = array_slice($words, 0, $i);
$parttwo = array_slice($words, $i);
$wordOne = implode("-" , $partOne);
$wordTwo = implode("-" , $partTwo);
/* SQL to select $wordOne and $wordTwo from the tables */
}
Related
I was wondering how would one create a function, in PHP, which is used for transposing some music chords.
I will try to explain how it works in music theory. I hope I don't forget something. If there are some mistakes, please help me to correct it.
1. The simple chords.
The simple chords are almost as simple as an alphabet and it goes like this:
C, C#, D, D#, E, F, F#, G, G#, A, A# B
From B it loops all over again to C. Therefore, If the original chord is E and we want to transpose +1, the resulting chord is F. If we transpose +4, the resulting chord is G#.
2. Expanded chords.
They work almost like the simple chords, but contain a few more characters, which can safely be ignored when transposing. For example:
Cmi, C#7, Dsus7, Emi, Fsus4, F#mi, G ...
So again, as with the simple chords, if we transpose Dsus7 + 3 = Fsus7
3. Non-root bass tone.
A problem arises when the bass plays a different tone than the chord root tone. This is marked by a slash after the chord and also needs to be transposed. Examples:
C/G, Dmi/A, F#sus7/A#
As with examples 1 and 2, everything is the same, but the part after the slash needs transpose too, therefore:
C/G + 5 = F/C
F#sus7/A# + 1 = Gsus7/B
So basically, imagine you have a PHP variable called chord and the transpose value transpose. What code would transpose the chord?
Examples:
var chord = 'F#sus7/C#';
var transpose = 3; // remember this value also may be negative, like "-4"
... code here ...
var result; // expected result = 'Asus7/E';
I have found an existed question on StackOverflow, at here. They talk about algorithm for chord-progressions.
How do I transpose music chords with PHP, by increasing or decreasing by semitones?
A quick solution:
<?php
// produces the expected result
echo transpose("F#sus7/C#",3);
function transpose($chord,$transpose)
{
// the chords
$chords = array("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B");
$result = "";
// get root tone
$root_arr = explode("/",$chord);
$root = strtoupper($root_arr[0]);
// the chord is the first character and a # if there is one
$root = $root[0].((strpos($root, "#") !== false)?"#":"");
// get any extra info
$root_extra_info = str_replace("#","",substr($root_arr[0],1)); // assuming that extra info does not have any #
// find the index on chords array
$root_index = array_search($root,$chords);
// transpose the values and modulo by 12 so we always point to existing indexes in our array
$root_transpose_index = floor(($root_index + $transpose) % 12);
if ($root_transpose_index < 0)
{
$root_transpose_index += 12;
}
$result.= $chords[$root_transpose_index].$root_extra_info;
if(count($root_arr)>1)
{
// get the non root tone
$non_root = $root_arr[1];
// the chord is the first character and a # if there is one
$non_root = strtoupper($non_root[0]).((strpos($non_root, "#") !== false)?"#":"");
// get any extra info
$non_root_extra_info = str_replace("#","",substr($root_arr[1],1)); // assuming that extra info does not have any #
// find the index on chords array
$non_root_index = array_search($non_root,$chords);
// transpose the values and modulo by 12 so we always point to existing indexes in our array
$non_root_transpose_index = floor(($non_root_index + $transpose) % 12);
if ($non_root_transpose_index < 0)
{
$non_root_transpose_index += 12;
}
$result.= "/".$chords[$non_root_transpose_index].$non_root_extra_info;
}
return $result;
}
https://3v4l.org/Cd9Pg
lots of room for improvement in code, i just tried to code it to be easy to understand.
Here my regex idea with preg_replace_callback (use of anonymous function requires PHP 5.3).
function transpose($str, $t=0)
{
// the chords
$chords = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];
// set transpose, return if none
$t = (int)$t % 12 + 12; if($t % 12 == 0) return $str;
// regex with callback
return preg_replace_callback('~[A-G]#?~', function($m) use (&$chords, &$t) {
return $chords[(array_search($m[0], $chords) + $t) % 12];
}, $str);
}
Demo at eval.in (for testing the regex pattern [A-G]#? see regex101)
echo transpose("Cmi, C#7, Dsus7, Emi, Fsus4, F#mi, G C/G, Dmi/A, F#sus7/A#", -3);
Ami, A#7, Bsus7, C#mi, Dsus4, D#mi, E A/E, Bmi/F#, D#sus7/G
Okay, so there are a few things you want to handle.
First, you want to be able to loop around in the array. That's easy: use the modulus operator, which in php is %.
function transpose($chord, $increment) {
$map = array('A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#');
// Get the index of the given chord
$index = array_search($chord, $map);
if($index === false)
return false;
// Get the transposed index and chord
$transpose_index = ($index + $increment) % count($map);
if($transpose_index < 0)
$transpose_index += count($map);
return $map[$transpose_index];
}
Second, you want to be able to strip out the actual chords that matter to you. You can do this using a regular expression (RegEx):
function transposeFull($chords, $increment) {
// This RegEx looks for one character (optionally followed by a sharp).
// .\#?
// This RegEx looks for an optional series of characters which are not /
// [^\/]*
// Put them together to get a RegEx that looks for an expanded chord
// (.\#?)([^\/]*)
// Then, do it again, but add a / first, and make it optional.
// (\/(.\#?)([^\/]*))?
$regex = '%(.\#?)([^\/]*)(\/(.\#?)([^\/]*))?%';
// Note that the () allow us to pull out the matches.
// $matches[0] is always the full thing.
// $matches[i] is the ith match
// (so $matches[3] is the whole optional second chord; which is not useful)
$matches = array();
preg_match($regex, $chords, $matches);
// Then, we get any parts that were matched and transpose them.
$chord1 = (count($matches) >= 2) ? transpose($matches[1], $increment) : false;
$expanded1 = (count($matches) >= 2) ? $matches[2] : '';
$chord2 = (count($matches) >= 5) ? transpose($matches[4], $increment) : false;
$expanded2 = (count($matches) >= 6) ? $matches[5] : '';
// Finally, put it back together.
$chords = '';
if($chord1 !== false)
$chords .= $chord1.$expanded1;
if($chord2 !== false)
$chords .= '/'.$chord2.$expanded2;
return $chords;
}
In PHP, if I have a long string, IE 10'000 chars, how would you suggest I go about finding the first occurence of a certain string before and after a given position.
IE, if I have the string:
BaaaaBcccccHELLOcccccBaaaaB
I can use strpos to find the position of HELLO. How could I then go about finding the position of the first occurence of B before HELLO and the first occurence of B after HELLO?
You can use stripos() and strripos() to find the first occurrence of a sub-string inside a string. You can also supply a negative offset to strripos() function to search in reverse order (from right to left). strripos() with negative offset
$body = "BaaaaBcccccHELLOcccccBaaaaB";
$indexOfHello = stripos($body, 'Hello');
if ($indexOfHello !== FALSE)
{
// First Occurrence of B before Hello
$indexOfB= stripos(substr($body,0,$indexOfHello),'B',($indexOfHello * -1));
print("First Occurance of B before Hello is ".$indexOfB."\n") ;
// First Occurrence of B before Hello (in reverse order)
$indexOfB= strripos($body,'B',($indexOfHello * -1));
print("First Occurrence of B before Hello (in reverse order) is ".$indexOfB."\n") ;
// First Occurrence of B after Hello
$indexOfB= stripos($body,'B',$indexOfHello);
print("First Occurance of B after Hello is ".$indexOfB."\n") ;
}
If you think about optimization there a lot of pattern search algorithms
Here is sample of naive pattern search:
/**
* Naive algorithm for Pattern Searching
*/
function search(string $pat, string $txt, int $searchFrom = 0, ?int $searchTill = null)
{
$M = strlen($pat);
$N = strlen($txt);
if ($searchTill !== null && $searchTill < $N){
$N = $searchTill;
}
for ($i = $searchFrom; $i <= $N - $M; $i++)
{
// For current index i,
// check for pattern match
for ($j = 0; $j < $M; $j++)
if ($txt[$i + $j] != $pat[$j])
break;
// if pat[0...M-1] =
// txt[i, i+1, ...i+M-1]
if ($j == $M)
return $i;
}
}
// Driver Code
$txt = "BaaaaBcccccHELLOcccccBaaaaB";
if (null!==($helloPos = search("HELLO", $txt))){
print("First Occurance of B before Hello is ".search("B", $txt, 0, $helloPos)."<br>") ;
print("First Occurance of B after Hello is ".search("B", $txt, $helloPos, null)."<br>") ;
}
Given the position…
To find the first occurrence before, you can take the substr() before the match and use strrpos().
To find the first occurrence after, you can still use strpos() and set the offset parameter.
Pattern search within a string.
for eg.
$string = "111111110000";
FindOut($string);
Function should return 0
function FindOut($str){
$items = str_split($str, 3);
print_r($items);
}
If I understand you correctly, your problem comes down to finding out whether a substring of 3 characters occurs in a string twice without overlapping. This will get you the first occurence's position if it does:
function findPattern($string, $minlen=3) {
$max = strlen($string)-$minlen;
for($i=0;$i<=$max;$i++) {
$pattern = substr($string,$i,$minlen);
if(substr_count($string,$pattern)>1)
return $i;
}
return false;
}
Or am I missing something here?
What you have here can conceptually be solved with a sliding window. For your example, you have a sliding window of size 3.
For each character in the string, you take the substring of the current character and the next two characters as the current pattern. You then slide the window up one position, and check if the remainder of the string has what the current pattern contains. If it does, you return the current index. If not, you repeat.
Example:
1010101101
|-|
So, pattern = 101. Now, we advance the sliding window by one character:
1010101101
|-|
And see if the rest of the string has 101, checking every combination of 3 characters.
Conceptually, this should be all you need to solve this problem.
Edit: I really don't like when people just ask for code, but since this seemed to be an interesting problem, here is my implementation of the above algorithm, which allows for the window size to vary (instead of being fixed at 3, the function is only briefly tested and omits obvious error checking):
function findPattern( $str, $window_size = 3) {
// Start the index at 0 (beginning of the string)
$i = 0;
// while( (the current pattern in the window) is not empty / false)
while( ($current_pattern = substr( $str, $i, $window_size)) != false) {
$possible_matches = array();
// Get the combination of all possible matches from the remainder of the string
for( $j = 0; $j < $window_size; $j++) {
$possible_matches = array_merge( $possible_matches, str_split( substr( $str, $i + 1 + $j), $window_size));
}
// If the current pattern is in the possible matches, we found a duplicate, return the index of the first occurrence
if( in_array( $current_pattern, $possible_matches)) {
return $i;
}
// Otherwise, increment $i and grab a new window
$i++;
}
// No duplicates were found, return -1
return -1;
}
It should be noted that this certainly isn't the most efficient algorithm or implementation, but it should help clarify the problem and give a straightforward example on how to solve it.
Looks like you more want to use a sub-string function to walk along and check every three characters and not just break it into 3
function fp($s, $len = 3){
$max = strlen($s) - $len; //borrowed from lafor as it was a terrible oversight by me
$parts = array();
for($i=0; $i < $max; $i++){
$three = substr($s, $i, $len);
if(array_key_exists("$three",$parts)){
return $parts["$three"];
//if we've already seen it before then this is the first duplicate, we can return it
}
else{
$parts["$three"] = i; //save the index of the starting position.
}
}
return false; //if we get this far then we didn't find any duplicate strings
}
Based on the str_split documentation, calling str_split on "1010101101" will result in:
Array(
[0] => 101
[1] => 010
[2] => 110
[3] => 1
}
None of these will match each other.
You need to look at each 3-long slice of the string (starting at index 0, then index 1, and so on).
I suggest looking at substr, which you can use like this:
substr($input_string, $index, $length)
And it will get you the section of $input_string starting at $index of length $length.
quick and dirty implementation of such pattern search:
function findPattern($string){
$matches = 0;
$substrStart = 0;
while($matches < 2 && $substrStart+ 3 < strlen($string) && $pattern = substr($string, $substrStart++, 3)){
$matches = substr_count($string,$pattern);
}
if($matches < 2){
return null;
}
return $substrStart-1;
Just like the title of this post says, I would to be able to check if every letter of a word is found in another word. So far these are the lines of codes that I was able to come up with:
<?php
$DBword = $_POST['DBword'];
$inputWords = $_POST['inputWords'];
$inputCount = str_word_count($inputWords,1);
echo "<b>THE WORD:</b>"."<br/>".$DBword."<br/><br/>";
echo "<b>WORDS ENTERED:</b><br/>";
foreach($inputCount as $outputWords)
{
echo $outputWords."<br/>";
}
foreach($inputCount as $countWords)
{
for($i=0; $i<strlen($countWords); $i++)
{$count = strpos( "$DBword", $countWords[$i]);}
if($count === false)
{
$score++;
}
}
echo "<b><br/>TOTAL SCORE: </b>";
echo $score;
?>
My point in having the foreach with the $outputWords is to just output the letters entered.
As for the other foreach that has $countWords, I am using it to really check if all letters in the word entered are found in the $DBword. I am using the for loop to check every letter.
So far, I am not getting the output that I want and I just ran out of ideas. Any ideas please?
function contains_letters($word1, $word2) {
for ($i = 0; $i < strlen($word1); $i++)
if (strpos($word2, $word1{$i}) === false)
return false;
return true;
}
//example usage
if (contains_letters($_POST['inputWords'], $_POST['DBword']))
echo "All the letters were found.";
If this check should be case-insensitive (i.e. 'A' counts as a usage of 'a'), change strpos to stripos.
Since you are overwriting $count in the for loop for each letter in $countWords, $count will contain the position of the last letter of $countWord only. Also, I am not sure why you increase score when the letter wasn't found.
In any case, you are making your life more difficult than necessary.
PHP has a function for counting chars in a string:
return count_chars($dbWord, 3) === count_chars($inputWord, 3);
will return true if the same letters are found in both strings.
Example to find all the words having exactly the same letters:
$dbWord = count_chars('foobar', 3);
$inputWords = 'barf boo oof raboof boarfo xyz';
print_r(
array_filter(
str_word_count($inputWords, 1),
function($inputWord) use ($dbWord) {
return count_chars($inputWord, 3) === $dbWord;
}
)
);
will output "raboof" and "boarfo" only.
I am trying to create a serial number checker.
Serial Numbers are in ranges
A87594 - A92778
AB34534 - AC23405
B23933 - C344444
I was able to get the numbers to work using range() for the first serial number example, I'm guessing I need to use explode() but I wasn't sure how to explode the letters into a variable and the numbers into a seperate variable.
if($_POST['submit']) {
$snum = $_POST['serial_number'];
// 1952
$jan01_jan07 = range(87594, 92478);
if (in_array($snum, $jan01_jan07)) {
echo 'You have a 1952 Widget';
}
else {
echo 'Your serial number is unknown';
}
}
You can try using strcmp, as it checks two strings, so you can check whether the incoming data is equal to or more than the lower bound and less than or equal to the upper bound, like this:
$data = $_POST['data']; // change this accordingly
if(strcmp($data, $lowerBound) >= 0 && strcmp($data, $upperBound) <= 0) {
// successful match
}
As strcmp returns -1, 0, 1 if $data is before, the same as and after $lowerBound (dictionary ordered), so this works for strings as well.
Try something along these lines:
preg_match('/([A-C]+)(\d+)/', $serial, $matches);
list(, $characters, $numbers) = $matches;
From there is kind of depends on the exact rules that govern your serials, something along these lines should do:
if ($characters == 'A' && 87594 <= $numbers && $numbers <= 92778) {
return true;
} else if ($characters == 'AB' …) ...