Unable to read blank spaces in string - php

What's wrong with this code. I want to read the number of blank spaces without using any built in function, but it wont return or read the blank spaces:
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while ($string[$i] != '' & $string[$i + 1] != '') {
if ($string[$i] == "" || empty($string[$i])) {
die("cdsd");
$breakposition = $string[$i];
$breakPoints++;
} else {
print_r($string[$i]);
}
$i++;
}
echo($breakPoints);
It's always going into the else part and never goes into the if statement. I even tried using isset() but that also didn't work. Where am I making a mistake?

Just loop while the string offset isset() and check if it equals a space. No need to do anything with $i+1:
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while (isset($string[$i])) {
if ($string[$i] == " ") {
$breakposition = $string[$i];
$breakPoints++;
} else {
print_r($string[$i]);
}
$i++;
}
echo($breakPoints);
This outputs:
canyoulookintothis??4

Once you've got your code right, you will always run into an string index error and you will need the isset() built in function to check before performing operations.
In other words, the i for the index will eventually point beyond the last letter of the string, this will cause a PHP error. You can use isset() to check for it and break out of the loop. Example:
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while (isset($string[$i])) {
if ($string[$i] == " ") {
$breakPoints++;
} else {
if($string[$i] != ''){
print_r($string[$i]);
}
}
$i++;
}
echo("<br />Number of spaces: ".$breakPoints

spaces is not empty, it will tack size.
so use this
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while ($string[$i] != '' & $string[$i + 1] != '') {
if ($string[$i] == " ") {
echo " ";
$breakposition = $string[$i];
$breakPoints++;
} else {
print_r($string[$i]);
}
$i++;
}
echo($breakPoints);
DEMO
or try this code,
use preg_match_all.
$matches = " ";
$numSpaces = preg_match_all('/[ ]/', $string , $matches);
or Use this::
substr_count($string , ' ');

Related

Php removing specific special character and php algorithm ideas

so I ended up with this project, that,due to my opinion, is some levels greater than my skills, so I would like you to help me.
This project's functionality is to write some words in those 4 columns,which have to be combined.The words that are in the same column mustn't be combined. You can only combine words with the rest of the columns.
I will give you the full code so you can see what I have done.
The second question I have is how you delete a special character(in this case, the "\n")
<?php
if(isset($_POST['submit']))
{
if(isset($_POST["separator"])){$separator= $_POST["separator"];}
if(isset($_POST["match"])){$matchType = $_POST["match"];$matchArr = array();
foreach($matchType as $match)
{
$matchArr = $match;
}}
$j=0;
$columnCount=array();
$wordArr[] = array();
$wordArrRows[] = array();
$protasi="";
$wordsCombinations = 1;
$wordsCounter = 0;
for($i=0; $i<4; $i++)
{ $words=0;
$enterChar=0;
if(isset($_POST["in$i"]) && !empty($_POST["in$i"]))
{
$input=$_POST["in$i"];
$enterChar = substr_count($input,"\n");
$words= $enterChar+1;
if($words>0)
{
$wordArr[$j]= explode("\n",$input);
$wordArrRows[$j]= $words;
$j++;
}
$wordsCombinations*=$words;
}
}
$i2=0;
$columnCounter = array_fill(0, $j, "0");
while($wordsCounter < $wordsCombinations)
{
if($i2<sizeof($columnCounter) && $columnCounter[$i2] < $wordArrRows[$i2])
{
echo "grammi: ".$i2." <br>";
$i=0;
for($i=0; $i<$j; $i++)
{
//echo "wordArr[".$i."][".$columnCounter[$i]."]".$separator;
echo $wordArr[$i][$columnCounter[$i]]." ";
}
$columnCounter[$i2]++;
if($columnCounter[$i2] >= $wordArrRows[$i2] ){$columnCounter[$i2]=0;}
echo "<br>";
}
$i2++;
if($i2>=sizeof($columnCounter)){$i2=0;}
$wordsCounter++;
}
}
?>
(NOTE: don't use the radio buttons or the check boxes, they're not functional).
EDIT
What is the expected result for that example?
The second question: trim() to delete "\n"

Is there anyway to repeat the biggest segment of continuous segment of repeat using php?

I want to put the input like "RKKRRRRK" and try to get the output like largest continuous segment.. Suppose my input may be "RKKKR" then my program will display 'KKK' is the largest continuous segment.. and then it also display the count is 3..
I've already write the code for counting 'R' values.. now i want this program also... need help anyone help me.. thanks in advance.
Here the code:-
<?php
function numberOfR($string1)
{
for($i=0;$i <strlen($string1);$i++)
{
if($string1[$i]!='K')
{
$count++;
}
}
return $count;
}
$return_value= numberOfR("RKKRK");
echo "R's count is:";
echo $return_value;
?>
<?php
function getLongetSegment($string) {
$currentSegmentChar='';
$currentSegment="";
$biggestSegment="";
$current_length=0;
$biggest_length=0;
for($i=0;$i<strlen($string);$i++) {
$char = $string[$i];
if($char != $currentSegmentChar || $currentSegmentChar == '') {
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
$biggest_length = $current_length;
}
$currentSegmentChar = $char;
$currentSegment = $char;
$current_length = 1;
}
elseif($currentSegmentChar != '') {
$currentSegment .= $char;
$current_length++;
}
}
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
}
return array("string" => $biggestSegment,"length" => $biggest_length);
}
print_r(getLongetSegment("RKKRGGG"));
?>
Result: GGG
You can use preg_match_all over here as
preg_match_all('/(.)\1+/i','RKKRRRRK',$res);
usort($res[0],function($a,$b){
return strlen($b) - strlen($a);
});
echo $res[0][0];
Not sure if I understood this quite right. Something like this:
function maxCharSequece($string1)
{
$maxSeq = $seq = 0;
$maxChar = $lastChar = null;
for( $i = 0; $i < strlen($string1); $i++ )
{
$c = $string1[$i];
if (!$lastChar) $lastChar = $c;
if ( $lastChar == $c ){
if ( ++$seq > $maxSeq ) $maxChar = $lastChar;
}
else {
$maxSeq = $seq;
$seq = 0;
}
}
return $maxChar;
}
You can use preg_replace_callback to receive all continuous segments and select the longest
$sq = '';
preg_replace_callback('/(.)\1+/',
function ($i) use (&$sq) {
if(strlen($i[0]) > strlen($sq)) $sq = $i[0];
}, $str);
echo $sq . " " . strlen($sq);

PHP - latex format of function with regex

Is it possible to write a regex which would take input like 'sqrt(2 * (2+2)) + sin(pi/6)' and transform it into '\sqrt{2 \cdot (2+2)} + \sin(\pi/6)'?
The problem is the 'sqrt' and parentheses in it. It is obvious I can't simply use something like this:
/sqrt\((.?)\)/ -> \\sqrt{$1}
because this code would create something like this '\sqrt{2 \cdot (2+2)) + \sin(\pi/6}'.
My solution: it simply go throw the string converted to char array and tests if a current substring starts with $latex, if it does second for-cycle go from this point in different direction and by parentheses decides where the function starts and ends. (startsWith function)
Code:
public static function formatFunction($function, $latex, $input) {
$input = preg_replace("/" . $function . "\(/", $latex . "{", $input);
$arr = str_split($input);
$inGap = false;
$gap = 0;
for ($i = count($arr) - 1; $i >= 0; $i--) {
if (startsWith(substr($input, $i), $latex)) {
for ($x = $i; $x < count($arr); $x++) {
if ($arr[$x] == "(" || $arr[$x] == "{") { $gap++; $inGap = true; }
else if ($arr[$x] == ")" || $arr[$x] == "}") { $gap--; }
if ($inGap && $gap == 0) {
$arr[$x] = "}";
$inGap = false;
break;
}
}
}
$gap = 0;
}
return implode($arr);
}
Use:
self::formatFunction("sqrt", "\\sqrt",
"sqrt(25 + sqrt(16 - sqrt(49)) + (7 + 1)) + sin(pi/2)");
Output:
\sqrt{25+\sqrt{16-\sqrt{49}}+(7+1)}+\sin (\pi/2)
Note: sin and pi aren't formated by this code, it's only str_replace function...
In general, no regular expression can effectively handle nested parentheses. Sorry to be the bearer of bad news! The MathJAX parser library can interpret LaTeX equations and you could probably add a custom output routine to do what you want.
For TeX questions, you can also try http://tex.stackexchange.com .
Some time ago i soved a similar problem in such way. Maybe it will be helpful for you
$str = 'sqrt((2 * (2+2)) + sin(pi/(6+7)))';
$from = []; // parentheses content
$to = []; // patterns for replace #<number>
$brackets = [['(', ')'], ['{', '}'], ['[', ']']]; // new parentheses for every level
$level = 0;
$count = 1; // count or replace made
while($count) {
$str = preg_replace_callback('(\(([^()]+)\))',
function ($m) use (&$to, &$from, $brackets, $level) {
array_unshift($to, $brackets[$level][0] . $m[1] . $brackets[$level][1]);
$i = '#' . (count($to)-1); // pattern for future replace.
// here it '#1', '#2'.
// Make it so they will be unique
array_unshift($from, $i);
return $i; }, $str, -1, $count);
$level++;
}
echo str_replace($from, $to, $str); // return content back
// sqrt[{2 * (2+2)} + sin{pi/(6+7)}]
I forgot all details, but it, seems, works

Replace commas for enum into pipes

whats is the best way to replace all commas for XX(a,s,d,f) into pipes in a long string like
`exp` x(10) XX('s','44','f','dd','sddd') some other text here, text here , other text here
i want to replace commas only in this XX('s','44','f','dd','sddd') part [commas only in the brackets]
Maybe something like:
while (preg_match('/\((.*),(.*)\)/', $foo))
$foo = preg_replace('/\((.*),(.*)\)/', '($1|$2)', $foo);
A simple string parser would probably be quicker than a regex. DEMO.
<?php
$string = "`exp` x(10) XX('s','44','f','dd','sddd') some other text here, text here , other text here";
$inParentheses = false;
for ($i = 0; $i < strlen($string); $i++) {
if ($inParentheses) {
if ($string[$i] == ")") {
$inParentheses = false;
} else if ($string[$i] == ",") {
$string[$i] = "|"; //The replacement character
}
} else if ($string[$i] == "(") {
$inParentheses = true;
}
}
var_dump($string);
?>
this is how i fixed it but still open for other solutions
while (preg_match('/\(([^\)]*)\)/', $tableCols)){
$tableCols = preg_replace('/\(([^\)]*)\)/e','"[[[".str_replace(\',\',\'|\',\'$1\')."]]]"', $tableCols);
}
$tableCols = str_replace('[[[', '(', $tableCols);
$tableCols = str_replace(']]]', ')', $tableCols);

Fast case counting

I have a large number of strings to process in php. I want to "fix" them to be title case (using ucwords(strtolower($str))) but only if they are all upper or all lower case already. If they are already mixed case, I'd just rather just leave them as they are.
What is the fastest way to check for this? It seems like foring through the string would be a rather slow way to go about it.
Here's what I have, which I think will be too slow:
function fixCase($str)
{
$uc = 0;
$lc = 0;
for($i=0;$i<strlen($str);$i++)
{
if ($str[$i] >= 'a' && $str[$i] <= 'z')
$lc++;
else if ($str[$i] >= 'A' && $str[$i] <= 'Z')
$uc++;
}
if ($uc == 0 || $lc == 0)
{
return ucwords(strtolower($str));
}
}
just use a string compare (case sensitive)
function fixCase($str)
{
if (
(strcmp($str, strtolower($str)) === 0) ||
(strcmp($str, strtoupper($str)) === 0) )
{
$str = ucwords(strtolower($str));
}
return $str;
}
There's not going to be any amazing optimization, because by the nature of the problem you need to look at every character.
Personally, I would just loop over the characters of the string with this sort of algorithm:
Look at the first character in the string, set a variable indicating whether it was upper or lowercase.
Now examine each character sequentially. If you get to the end of the string and they've all been the same case as the first character, fix the string's case as you like.
If any character is a different case than the first character was, break the loop and return the string.
Edit: actual code, I think this is about as good as you're going to get.
// returns 0 if non-alphabetic char, 1 if uppercase, 2 if lowercase
function getCharType($char)
{
if ($char >= 'A' && $char <= 'Z')
{
return 1;
}
else if ($char >= 'a' && $char <= 'z')
{
return 2;
}
else
{
return 0;
}
}
function fixCase($str)
{
for ($i = 0; $i < strlen($str); $i++)
{
$charType = getCharType($str[$i]);
if ($charType != 0)
{
$firstCharType = $charType;
break;
}
}
for ($i = $i + 1; $i < strlen($str); $i++)
{
$charType = getCharType($str[$i]);
if ($charType != $firstCharType && $charType != 0)
{
return $str;
}
}
if ($firstCharType == 1) // uppercase, need to convert to lower first
{
return ucwords(strtolower($str));
}
else if ($firstCharType == 2) // lowercase, can just ucwords() it
{
return ucwords($str);
}
else // there were no letters at all in the string, just return it
{
return $str;
}
}
You could try the string case test function I posted here
function getStringCase($subject)
{
if (!empty($subject))
{
if (preg_match('/^[^A-Za-z]+$/', $subject))
return 0; // no alphabetic characters
else if (preg_match('/^[^A-Z]+$/', $subject))
return 1; // lowercase
else if (preg_match('/^[^a-z]+$/', $subject))
return 2; // uppercase
else
return 3; // mixed-case
}
else
{
return 0; // empty
}
}
If the reason you want to avoid fixing already mixed-case strings is for efficiency then you are likely wasting your time, convert every string no matter its current condition:
function fixCase($str)
{
return ucwords(strtolower($str));
}
I would be very surprised if it ran any slower than the accepted answer for strings the length of those you would generally want to title case, and it's one less condition you need to worry about.
If, however, there is good reason to avoid converting already mixed-case strings, for example you want to preserve some intended meaning in the casing, then yes, jcinacio's answer is certainly the simplest and very efficient.
Wouldn't it be easier to check if the string = lowercase(string) or string = uppercase(string) and if so then leave it. Otherwise perform your operation.
Well I decided to do a test of the 2 proposed answers thus far and my original solution. I wouldn't have thought the results would turn out this way, but I guess native methods are /that/ much faster over all.
Code:
function method1($str)
{
if (strcmp($str, strtolower($str)) == 0)
{
return ucwords($str);
}
else if (strcmp($str, strtoupper($str)) == 0)
{
return ucwords(strtolower($str));
}
else
{
return $str;
}
}
// returns 0 if non-alphabetic char, 1 if uppercase, 2 if lowercase
function getCharType($char)
{
if ($char >= 'A' && $char <= 'Z')
{
return 1;
}
else if ($char >= 'a' && $char <= 'z')
{
return 2;
}
else
{
return 0;
}
}
function method2($str)
{
for ($i = 0; $i < strlen($str); $i++)
{
$charType = getCharType($str[$i]);
if ($charType != 0)
{
$firstCharType = $charType;
break;
}
}
for ($i = $i + 1; $i < strlen($str); $i++)
{
$charType = getCharType($str[$i]);
if ($charType != $firstCharType && $charType != 0)
{
return $str;
}
}
if ($firstCharType == 1) // uppercase, need to convert to lower first
{
return ucwords(strtolower($str));
}
else if ($firstCharType == 2) // lowercase, can just ucwords() it
{
return ucwords($str);
}
else // there were no letters at all in the string, just return it
{
return $str;
}
}
function method0($str)
{
$uc = 0;
$lc = 0;
for($i=0;$i<strlen($str);$i++)
{
if ($str[$i] >= 'a' && $str[$i] <= 'z')
$lc++;
else if ($str[$i] >= 'A' && $str[$i] <= 'Z')
$uc++;
}
if ($uc == 0 || $lc == 0)
{
return ucwords(strtolower($str));
}
}
function test($func,$s)
{
$start = gettimeofday(true);
for($i = 0; $i < 1000000; $i++)
{
$s4 = $func($s);
}
$end = gettimeofday(true);
echo "$func Time: " . ($end-$start) . " - Avg: ".sprintf("%.09f",(($end-$start)/1000000))."\n";
}
$s1 = "first String";
$s2 = "second string";
$s3 = "THIRD STRING";
test("method0",$s1);
test("method0",$s2);
test("method0",$s3);
test("method1",$s1);
test("method1",$s2);
test("method1",$s3);
test("method2",$s1);
test("method2",$s2);
test("method2",$s3);
Results:
method0 Time: 19.2899270058 - Avg: 0.000019290
method0 Time: 20.8679389954 - Avg: 0.000020868
method0 Time: 24.8917310238 - Avg: 0.00002489
method1 Time: 3.07466816902 - Avg: 0.000003075
method1 Time: 2.52559089661 - Avg: 0.000002526
method1 Time: 4.06261897087 - Avg: 0.000004063
method2 Time: 19.2718701363 - Avg: 0.000019272
method2 Time: 35.2485661507 - Avg: 0.000035249
method2 Time: 29.3357679844 - Avg: 0.000029336
Note that anything that looks only at [A-Z] will be incorrect as soon as there are accented or umlaut characters. Optimizing for speed is meaningless if the result is incorrect (hey, if the result doesn't have to be correct, it can write you a REALLY fast implementation...)

Categories