How can I convert the text case-sensivite with str_ireplace? [duplicate] - php

I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.
Example:
Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.
I want to replace word 'place' with 'garden'.
Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.
It should also work with phrases.

I've created a function that will replace the word for you and keep the cases.
function replaceWithCase($source, $replacement, $string) {
// Does the string contain the source word?
if (strpos($string, $source) === false) {
return false;
}
// If everything is uppercase, return the replacement fully uppercase
if (ctype_upper($source)) {
return str_replace($source, strtoupper($replacement));
}
// Set an array to work with
$characters = array();
// Split the source into characters
$sourceParts = explode('', $source);
// Loop throug the characters and set the case
foreach ($sourceParts as $k => $sp) {
if (ctype_upper($sp)) {
$characters[$k] = true;
} else {
$characters[$k] = false;
}
}
// Split the replacement into characters
$replacementParts = explode('', $replacement);
// Loop through characters and compare their case type
foreach ($replacementParts as $k => $rp) {
if (array_key_exists($k, $characters) && $characters[$k] === true) {
$newWord[] = strtoupper($rp);
} else {
$newWord[] = strtolower($rp);
}
}
return substr_replace($source, implode('', $newWord), $string);
}
// usage
echo replaceWithCase('AppLes', 'bananas', 'Comparing AppLes to pears');
Note: it is untested and might need some tweaking

function stringReplace($findStr, $replaceStr, $str)
{
$isLowerStr = true;
for($i=0; $i<strlen($findStr); $i++){
if(ord($findStr[$i]) >= 97 && ord($findStr[$i])<=122){
if(ord($replaceStr[$i]) >= 65 && ord($replaceStr[$i])<=96){
$replaceStr[$i] = strtolower($replaceStr[$i]);
}else{
$replaceStr[$i] = $replaceStr[$i];
}
}else{
$isLowerStr = false;
$replaceStr[$i] = strtoupper($replaceStr[$i]);
}
}
if($isLowerStr == false){
if(strlen($replaceStr) > strlen($findStr)){
for($i=0;$i<(strlen($replaceStr)-strlen($findStr));$i++){
if(strtoupper($findStr) == $findStr){
$replaceStr[strlen($findStr)+$i] = strtoupper($replaceStr[strlen($findStr)+$i]);
}else{
$replaceStr[strlen($findStr)+$i] = strtolower($replaceStr[strlen($findStr)+$i]);
}
}
}
}
echo str_replace($findStr, $replaceStr, $str);die;
}
$findStr = 'Place';
$replaceStr = 'garden';
echo stringReplace($findStr, $replaceStr, 'Potato is jumping all over the '.$findStr.'.');

So I managed to create my own function in the end. Thanks for help and inspiration though.
function replaceWithCase($source, $replacement, $string, $pos = 0) {
while (($pos = strpos(strtolower($string), strtolower($source), $pos))!== false) {
$substr = mb_substr($string, $pos, strlen($source));
$remaining = mb_substr($string, $pos + strlen($source));
if (ctype_upper($substr)) {
$string = substr_replace($string,strtoupper($replacement),$pos,strlen($source));
continue;
}
$substrParts = preg_split('//u', $substr, null, PREG_SPLIT_NO_EMPTY);
$replaceParts = preg_split('//u', $replacement, null, PREG_SPLIT_NO_EMPTY);
$newWord = '';
foreach ($replaceParts as $k => $rp) {
if (array_key_exists($k,$substrParts))
$newWord .= ctype_upper($substrParts[$k]) ? mb_strtoupper($rp) : mb_strtolower($rp);
else
$newWord .= $rp;
}
$string = substr_replace($string,$newWord,$pos,strlen($source));
$pos = $pos + strlen($source);
}
return $string;
}
echo replaceWithCase("place", "garden", "Potato is jumping all over the PLACE");
echo "<br>";
echo replaceWithCase("jumping", "running", "Potato is jumping all over the pLAcE");
echo "<br>";
echo replaceWithCase("jumping", "cry", "Potato is jumping all over the place");
echo "<br>";
echo replaceWithCase("all", "", "Potato is jumping all over the Place");
echo "<br>";
echo replaceWithCase(" ", ";", "Potato is jumping all over the Place", 10);
echo "<br>";
Output:
Potato is jumping all over the GARDEN
Potato is running all over the pLAcE
Potato is cry all over the place
Potato is jumping over the Place
Potato is jumping;all;over;the;Place

Thanks #LadaB - that's a really helpful function but it also replaces partial word matches. Sometimes you might want this, but in others cases you won't, for example if you have:
$source = 'mom';
$replacement = 'mum'; // british spelling of "mom"
$string = 'Be in the moment with your Mom.';
You get: "Be in the mument with your Mum."
So, I have added an option to make the match "whole word only".
I found another issue where multibyte characters would shift where the capitalization ended up, which seems to be fixed by changing. mb_substr to substr.
I also removed the unused:
$remaining = substr($string, $pos + strlen($source));
My latest (I think fully working) version is:
function replaceWithCase($source, $replacement, $string, $wholeWordOnly = false) {
$pos = 0;
while (($pos = strpos(strtolower($string), strtolower($source), $pos))!== false) {
if($wholeWordOnly) {
preg_match("/\b".$string[$pos]."/", $string[($pos-1)] . $string[$pos], $start);
preg_match("/".$string[($pos+strlen($source)-1)]."\b/", $source . $string[($pos+strlen($source))], $end);
}
if(($wholeWordOnly && $start && $end) || !$wholeWordOnly) {
$substr = substr($string, $pos, strlen($source));
if (ctype_upper($substr)) {
$string = substr_replace($string,strtoupper($replacement),$pos,strlen($source));
continue;
}
$substrParts = preg_split('//u', $substr, -1, PREG_SPLIT_NO_EMPTY);
$replaceParts = preg_split('//u', $replacement, -1, PREG_SPLIT_NO_EMPTY);
$newWord = '';
foreach ($replaceParts as $k => $rp) {
if (array_key_exists($k,$substrParts))
$newWord .= ctype_upper($substrParts[$k]) ? mb_strtoupper($rp) : mb_strtolower($rp);
else
$newWord .= $rp;
}
$string = substr_replace($string,$newWord,$pos,strlen($source));
}
$pos = $pos + strlen($source);
}
return $string;
}
Hope that helps you or someone else.

Use "stripos" php function
$str = 'Potato is jumping all over the pLAcEs.';
$str_new = "garden";
$str1 = str_split($str_new);
$pos = stripos($str,'places');
$string = substr($str,$pos,6);
$extrct = str_split($string);
$var = '';
foreach ($extrct as $key => $value) {
if(ctype_upper($value))
{
$var .= strtoupper($str1[$key]);
}else{
$var .= strtolower($str1[$key]);
}
}
$new_string = str_replace($string, $var, $str);
echo $new_string; //Potato is jumping all over the gARdEn.

Related

Check if a word has multiple uppercases letters and only change the words who have One and only uppercase (and be the first letter )

My code so far:
$text = 'Herman Archer LIVEs in neW YORK';
$oldWords = explode(' ', $text);
$newWords = array();
$counter = 0;
foreach ($oldWords as $word) {
for($k=0;$k<strlen($word);$k++)
$counter = 0;
if ($word[k] == strtoupper($word[$k]))
$counter=$counter+1;
if($counter>1)
$word = strtolower($word);
if($counter == 1)
$word = ucfirst(strtolower($word));
else $word = strtolower($word);
echo $word."<br>";
}
Result:
Herman
Archer
Lives
In
New
York
Expected output:
Herman Archer lives in new york
If you want to use the counter approach you could use something as the following
<?php
$text = 'Herman Archer LIVEs in A neW YORK';
$words = explode(' ', $text);
foreach($words as &$word) {
$counter = 0;
for($i = 1; $i <= strlen($word);$i++) {
if (strtoupper($word[$i]) == $word[$i]) $counter++;
if ($counter == 2) break;
}
if ($counter == 2) $word = strtolower($word);
}
echo implode(' ', $words);
Let's do it in a simple manner. Let's loop $oldWords, compare the strings from the second character to the end with their lower-case version and replace if the result is different.
for ($index = 0; $index < count($oldWords); $index++) {
//Skip one-lettered words, such as a or A
if (strlen($oldWords[$index]) > 1) {
$lower = strtolower($oldWords[$index]);
if (substr($oldWords[$index], 1) !== substr($lower, 1)) {
$oldWords[$index] = $lower;
}
}
}
If you are using not only English language, you might want to switch to mb_strtolower
<?php
$text = 'Herman Archer LIVEs in neW YORK';
function normalizeText($text)
{
$words = explode(" ", $text);
$normalizedWords = array_map(function ($word) {
$loweredWord = strtolower($word);
if (ucfirst($loweredWord) === $word) {
return $word;
}
return $loweredWord;
}, $words);
return join(" ", $normalizedWords);
}
echo normalizeText($text) . PHP_EOL; // Herman Archer lives in new york
you can combine ctype_upper for first character and ctype_lower for the rest
$text = 'Herman Archer LIVEs in neW YORK';
$oldWords = explode(' ', $text);
$newWords = '';
foreach ($oldWords as $word) {
if(ctype_upper($word[0])&&ctype_lower(substr($word,1))){
$newWords .= $word.' ';
}else{
$newWords .= strtolower($word).' ';
}
}
echo $newWords;
Meanwhile I've found out that this can be done in an easier way
if(isset($_POST["sumbit"])){
$string = $_POST["string"];
if(!empty($string)){
$word = explode (" ",$string);
foreach($words as $word){
//cut the first letter.
//check caselower.
//if not, attach the letter back and turn all lowercase.
//if yes, attach the letter back and leave it .
$wordCut = substr($word,1);
if(ctype_lower($wordCut)){
echo $word." ";
} else {
echo strtolower($word). " ";
}
}

How to find exact or closest match from a large array, in a big string?

Consider the following. I have a very large array with all the road names in a given country, ordered by string length like this:
$roadNames = ['Ivy Lane','East Road','The Maltings','Greenhill Road', 'Woodlands Close']; //And many, many more
Now i want look for an exact match in a in a long string
$string = "
..... ALOT OF TEXT .....
..... ALOT OF TEXT .....
You can find us at: Greenhill Road 1, 11111, The City
..... ALOT OF TEXT .....
..... ALOT OF TEXT .....
";
To find an exact match, witch is fairly easy, I just do the following:
foreach ($roadNames as $roadName) {
if(stripos($string, $roadName) !== false){
echo 'Exact match: '.$roadName;
break;
}
}
But what if the road name is misspelled by 1 letter, fx. an extra space / a space is missing, a letter less/more, or 1 letter is wrong. Fx. "Greenhil Road", "Greenhilll Road", "GreenhillRoad", "Green hill Road", "Creenhill Road"? How can i now find the best match of all my road names in the array if the the road name in the $string was one of the examples? Is there any mathematics way to do it? Or maybe i can buid a regex?
I am thinking something like this, although it seems like overkill (And does not work)
foreach ($roadNames as $roadName) {
if (stripos($string, $roadName)) {
echo 'Exact match: ' . $roadName;
break;
} else {
$alphabet = range('a', 'z');
$alphabet[] = ' ';
$roadName_split = str_split($roadName);
$test_array = array();
foreach ($roadName_split as $strpos => $letter) {
foreach ($alphabet as $letter_in_alphabet) {
$test_array[] = $letter_in_alphabet;
}
foreach ($test_array as $key => $value) {
$test_array[$key] .= substr($roadName, $strpos, 1);
}
}
echo '<pre>';
print_r($test_array);
echo '</pre>';
die;
foreach ($test_array as $misplled_value) {
if (stripos($string, $misplled_value)) {
echo 'close match found: ' . $roadName;
break;
}
}
// OR Some kind of a regex, dont know how it should be
// $roadName_split = str_split($roadName);
// $re = '';
// foreach ($roadName_split as $strpos => $letter) {
// $re .= "$letter?";
// }
}
}
I finally found a solution with inspiration from: https://stackoverflow.com/a/1720798/2192013
I make a regex from each roadName, allowing 1 letter to be misspelled, 1 letter or space, too short or too much, with this function:
function generateRegex($word) {
$len = strlen($word);
$regex = "/(($word)";
$word_split = str_split($word);
foreach ($word_split as $strpos => $letter) {
$temp = $word;
$temp[$strpos - 1] = '.';
if ($strpos === 0) {
$temp1 = substr($word, ($strpos + 1));
$temp2 = '.' . substr($word, $strpos);
} else {
$temp1 = substr($word, 0, $strpos) . substr($word, ($strpos + 1));
$temp2 = substr($word, 0, $strpos) . '.' . substr($word, $strpos);
}
$regex .= "|($temp)";
$regex .= "|($temp1)";
$regex .= "|($temp2)";
}
$regex = $regex . ")/mi";
return $regex;
}
$temp take cares of 1 letter misspelled (Ex. Creenhill Road) and are
replacing 1 letter with a dot, as many times as possible
$temp1 takes care of 1 letter/space too short (Ex. Grenhill Road OR
GreenhillRoad) and are removing 1 letter, as many times as possible
$temp2 takes care of 1 letter/space too much (Ex. Green hill Road OR
Greennhill Road) and are adding a dot to each letter, as many times
as possible
So the final script looks like this:
function generateRegex($word) {
$len = strlen($word);
$regex = "/(($word)";
$word_split = str_split($word);
foreach ($word_split as $strpos => $letter) {
$temp = $word;
$temp[$strpos - 1] = '.';
if ($strpos === 0) {
$temp1 = substr($word, ($strpos + 1));
$temp2 = '.' . substr($word, $strpos);
} else {
$temp1 = substr($word, 0, $strpos) . substr($word, ($strpos + 1));
$temp2 = substr($word, 0, $strpos) . '.' . substr($word, $strpos);
}
$regex .= "|($temp)";
$regex .= "|($temp1)";
$regex .= "|($temp2)";
}
$regex = $regex . ")/mi";
return $regex;
}
function findBestMatch($roadNames, $string) {
foreach ($roadNames as $roadName) {
if (stripos($string, $roadName)) {
$return = 'Exact match found: ' . $roadName;
break;
} else {
$re = generateRegex($roadName);
if (preg_match($re, $string)) {
$return = 'Close match found: ' . $roadName;
break;
}
}
}
if (!isset($return) OR empty($return)) {
return 'Match not found';
} else {
return $return;
}
}
$roadNames = ['Greenhill Road', 'Ivy Lane', 'East Road', 'The Maltings', 'Woodlands Close']; //And many, many more
$misspelled_examples = ['Greenhill Road', 'Crennhill Road', 'Green hill Road', 'Greennhill Road', 'GreenhillRoad', 'Grenhill Road', 'GrenhilRoad'];
foreach ($misspelled_examples as $value) {
$strings[] = "
..... ALOT OF TEXT .....
..... ALOT OF TEXT .....
You can find us at: $value 1, 11111, The City
..... ALOT OF TEXT .....
..... ALOT OF TEXT .....
";
}
foreach ($strings as $key => $string) {
echo 'Input road-name: ' . $misspelled_examples[$key];
echo '<br>';
echo findBestMatch($roadNames, $string);
echo '<hr>';
}

How to replace string with another string and keep case in php and mysql?

I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.
Example:
Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.
I want to replace word 'place' with 'garden'.
Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.
It should also work with phrases.
I've created a function that will replace the word for you and keep the cases.
function replaceWithCase($source, $replacement, $string) {
// Does the string contain the source word?
if (strpos($string, $source) === false) {
return false;
}
// If everything is uppercase, return the replacement fully uppercase
if (ctype_upper($source)) {
return str_replace($source, strtoupper($replacement));
}
// Set an array to work with
$characters = array();
// Split the source into characters
$sourceParts = explode('', $source);
// Loop throug the characters and set the case
foreach ($sourceParts as $k => $sp) {
if (ctype_upper($sp)) {
$characters[$k] = true;
} else {
$characters[$k] = false;
}
}
// Split the replacement into characters
$replacementParts = explode('', $replacement);
// Loop through characters and compare their case type
foreach ($replacementParts as $k => $rp) {
if (array_key_exists($k, $characters) && $characters[$k] === true) {
$newWord[] = strtoupper($rp);
} else {
$newWord[] = strtolower($rp);
}
}
return substr_replace($source, implode('', $newWord), $string);
}
// usage
echo replaceWithCase('AppLes', 'bananas', 'Comparing AppLes to pears');
Note: it is untested and might need some tweaking
function stringReplace($findStr, $replaceStr, $str)
{
$isLowerStr = true;
for($i=0; $i<strlen($findStr); $i++){
if(ord($findStr[$i]) >= 97 && ord($findStr[$i])<=122){
if(ord($replaceStr[$i]) >= 65 && ord($replaceStr[$i])<=96){
$replaceStr[$i] = strtolower($replaceStr[$i]);
}else{
$replaceStr[$i] = $replaceStr[$i];
}
}else{
$isLowerStr = false;
$replaceStr[$i] = strtoupper($replaceStr[$i]);
}
}
if($isLowerStr == false){
if(strlen($replaceStr) > strlen($findStr)){
for($i=0;$i<(strlen($replaceStr)-strlen($findStr));$i++){
if(strtoupper($findStr) == $findStr){
$replaceStr[strlen($findStr)+$i] = strtoupper($replaceStr[strlen($findStr)+$i]);
}else{
$replaceStr[strlen($findStr)+$i] = strtolower($replaceStr[strlen($findStr)+$i]);
}
}
}
}
echo str_replace($findStr, $replaceStr, $str);die;
}
$findStr = 'Place';
$replaceStr = 'garden';
echo stringReplace($findStr, $replaceStr, 'Potato is jumping all over the '.$findStr.'.');
So I managed to create my own function in the end. Thanks for help and inspiration though.
function replaceWithCase($source, $replacement, $string, $pos = 0) {
while (($pos = strpos(strtolower($string), strtolower($source), $pos))!== false) {
$substr = mb_substr($string, $pos, strlen($source));
$remaining = mb_substr($string, $pos + strlen($source));
if (ctype_upper($substr)) {
$string = substr_replace($string,strtoupper($replacement),$pos,strlen($source));
continue;
}
$substrParts = preg_split('//u', $substr, null, PREG_SPLIT_NO_EMPTY);
$replaceParts = preg_split('//u', $replacement, null, PREG_SPLIT_NO_EMPTY);
$newWord = '';
foreach ($replaceParts as $k => $rp) {
if (array_key_exists($k,$substrParts))
$newWord .= ctype_upper($substrParts[$k]) ? mb_strtoupper($rp) : mb_strtolower($rp);
else
$newWord .= $rp;
}
$string = substr_replace($string,$newWord,$pos,strlen($source));
$pos = $pos + strlen($source);
}
return $string;
}
echo replaceWithCase("place", "garden", "Potato is jumping all over the PLACE");
echo "<br>";
echo replaceWithCase("jumping", "running", "Potato is jumping all over the pLAcE");
echo "<br>";
echo replaceWithCase("jumping", "cry", "Potato is jumping all over the place");
echo "<br>";
echo replaceWithCase("all", "", "Potato is jumping all over the Place");
echo "<br>";
echo replaceWithCase(" ", ";", "Potato is jumping all over the Place", 10);
echo "<br>";
Output:
Potato is jumping all over the GARDEN
Potato is running all over the pLAcE
Potato is cry all over the place
Potato is jumping over the Place
Potato is jumping;all;over;the;Place
Thanks #LadaB - that's a really helpful function but it also replaces partial word matches. Sometimes you might want this, but in others cases you won't, for example if you have:
$source = 'mom';
$replacement = 'mum'; // british spelling of "mom"
$string = 'Be in the moment with your Mom.';
You get: "Be in the mument with your Mum."
So, I have added an option to make the match "whole word only".
I found another issue where multibyte characters would shift where the capitalization ended up, which seems to be fixed by changing. mb_substr to substr.
I also removed the unused:
$remaining = substr($string, $pos + strlen($source));
My latest (I think fully working) version is:
function replaceWithCase($source, $replacement, $string, $wholeWordOnly = false) {
$pos = 0;
while (($pos = strpos(strtolower($string), strtolower($source), $pos))!== false) {
if($wholeWordOnly) {
preg_match("/\b".$string[$pos]."/", $string[($pos-1)] . $string[$pos], $start);
preg_match("/".$string[($pos+strlen($source)-1)]."\b/", $source . $string[($pos+strlen($source))], $end);
}
if(($wholeWordOnly && $start && $end) || !$wholeWordOnly) {
$substr = substr($string, $pos, strlen($source));
if (ctype_upper($substr)) {
$string = substr_replace($string,strtoupper($replacement),$pos,strlen($source));
continue;
}
$substrParts = preg_split('//u', $substr, -1, PREG_SPLIT_NO_EMPTY);
$replaceParts = preg_split('//u', $replacement, -1, PREG_SPLIT_NO_EMPTY);
$newWord = '';
foreach ($replaceParts as $k => $rp) {
if (array_key_exists($k,$substrParts))
$newWord .= ctype_upper($substrParts[$k]) ? mb_strtoupper($rp) : mb_strtolower($rp);
else
$newWord .= $rp;
}
$string = substr_replace($string,$newWord,$pos,strlen($source));
}
$pos = $pos + strlen($source);
}
return $string;
}
Hope that helps you or someone else.
Use "stripos" php function
$str = 'Potato is jumping all over the pLAcEs.';
$str_new = "garden";
$str1 = str_split($str_new);
$pos = stripos($str,'places');
$string = substr($str,$pos,6);
$extrct = str_split($string);
$var = '';
foreach ($extrct as $key => $value) {
if(ctype_upper($value))
{
$var .= strtoupper($str1[$key]);
}else{
$var .= strtolower($str1[$key]);
}
}
$new_string = str_replace($string, $var, $str);
echo $new_string; //Potato is jumping all over the gARdEn.

Regex for route matching in PHP

I am working on my mini url router in PHP. So far I've got regex for extracting variables in the url enclosed in {}(By looking at Symfony's router code) :
public function parse($pattern)
{
$matches = '';
$variables = array();
$pos = 0;
preg_match_all('#\{\w+\}#', $pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
foreach ($matches as $match)
{
$varName = substr($match[0][0], 1, -1);
if(is_numeric($varName)) {
throw new Exception('Argument cannot be a number');
}
if (in_array($varName, $variables)) {
throw new \LogicException(sprintf('More then one occurrence of variable name "%s".', $varName));
}
$variables[] = $varName;
}
return ['variables' => $variables];
}
So this method extracts the vars, now I need a regex to match the pattern of the route with the url. I started learning about regexes, but I still am not that good to wrap my head around this.
This will work: \/hello\/{?([^\/}]+)}?
(At least it does on the examples you provided:)
/hello/{name}
/hello/Sam
Explanation
\/ is an escaped /
hello finds hello, in case you didn't realize.
{? finds a {, if there is one.
([^\/}]+) finds everything that's not a / or }
}? finds a }, if there is one.
For anyone that might be interested, I got it, thanks to Laurel's answer.
This is the updated version of the method it still needs some work though :
$matches = '';
$variables = array();
$pos = 0;
$reg = '#';
$nextText = '';
preg_match_all('#\{\w+\}#', $pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
foreach ($matches as $match)
{
$varName = substr($match[0][0], 1, -1);
$precedingText = substr($pattern, $pos, $match[0][1] - $pos);
$pos = $match[0][1] + strlen($match[0][0]);
$nxt = $pos - strlen($pattern);
if($nxt == 0) $nxt = strlen($pattern);
$nextText = substr($pattern, $nxt);
//$precedingText = substr($precedingText, 1, -1);
$precSegments = explode('/', $precedingText);
$precSegments = array_splice($precSegments, 1);
//$temp = 5;
echo 'nxt ' . $nextText . '<><br>';
if(strlen($precedingText) > 1)
{
foreach($precSegments as $key => $value)
{
$reg .= '\/';
$reg .= $value;
}
$reg .= '{?([^\/}]+)}?';
}
else
{
$reg .= '{?([^\/}]+)}?';
}
$nextText = str_replace('/', '\/', $nextText);
if(is_numeric($varName)) {
throw new Exception('Argument cannot be a number');
}
if (in_array($varName, $variables)) {
throw new \LogicException(sprintf('More then one occurrence of variable name "%s".', $varName));
}
$variables[] = $varName;
}
if(count($matches) < 1)
{
$reg .= str_replace('/', '\/', $pattern);
}
$reg = $reg . $nextText;
$reg .= '#';
if($pattern == '/')
{
$reg = '#^[\/]+$#';
}
return ['variables' => $variables, 'regex' => $reg];

match the first & last whole word in a variable

I use php preg_match to match the first & last word in a variable with a given first & last specific words,
example:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '(.*)' . $last_word .'$/' , $str))
{
echo 'true';
}
But the problem is i want to force match the whole word at (starting & ending) not the first or last characters.
Using \b as boudary word limit in search:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '\b(.*)\b' . $last_word .'$/' , $str))
{
echo 'true';
}
I would go about this in a slightly different way:
$firstword = 't';
$lastword = 'ne';
$string = 'this function can be done';
$words = explode(' ', $string);
if (preg_match("/^{$firstword}/i", reset($words)) && preg_match("/{$lastword}$/i", end($words)))
{
echo 'true';
}
==========================================
Here's another way to achieve the same thing
$firstword = 'this';
$lastword = 'done';
$string = 'this can be done';
$words = explode(' ', $string);
if (reset($words) === $firstword && end($words) === $lastword)
{
echo 'true';
}
This is always going to echo true, because we know the firstword and lastword are correct, try changing them to something else and it will not echo true.
I wrote a function to get Start of sentence but it is not any regex in it.
You can write for end like this. I don't add function for the end because of its long...
<?php
function StartSearch($start, $sentence)
{
$data = explode(" ", $sentence);
$flag = false;
$ret = array();
foreach ($data as $val)
{
for($i = 0, $j = 0;$i < strlen($val), $j < strlen($start);$i++)
{
if ($i == 0 && $val{$i} != $start{$j})
break;
if ($flag && $val{$i} != $start{$j})
break;
if ($val{$i} == $start{$j})
{
$flag = true;
$j++;
}
}
if ($j == strlen($start))
{
$ret[] = $val;
}
}
return $ret;
}
print_r(StartSearch("th", $str));
?>

Categories