I have this code:
$CapDeliveryCityANDState = str_replace('\, ', '\,', ucwords(str_replace('\,', '\, ', strtolower($CapDeliveryCityANDState))));
$CapDeliveryCityANDState = strrev(ucfirst(strrev($CapDeliveryCityANDState)));
that makes the first letter capital of every word and the rest lowercase and after the comma "," it makes the first two letters capital, but I want to add another thing and to make a letter capital if there is a "'" so, so far what I have works great for this example:
cHiCago, il would become Chicago, IL
but if it was o'fallon, mo it would be O'fallon, MO but I would like it to be O'Fallon, MO (capital after the apostrophe)
Thanks for the help...
SOLUTION IS:
$CapDeliveryCityANDState = str_replace('\, ', '\,', ucwords(str_replace('\,', '\, ', strtolower($CapDeliveryCityANDState))));
$CapDeliveryCityANDState = strrev(ucfirst(strrev($CapDeliveryCityANDState)));
if(strpos($CapDeliveryCityANDState, "'")) {
$pos = strpos($CapDeliveryCityANDState, "'") + 1;
}
$CapDeliveryCityANDState = substr_replace($CapDeliveryCityANDState, strtoupper($CapDeliveryCityANDState[$pos]), $pos, 1);
$CapDeliveryCityANDState[$l=strlen($CapDeliveryCityANDState)-2] = strtoupper($CapDeliveryCityANDState[$l]);
Added more to this code for anyone if they ever need it:
$CapDeliveryCityANDState = $contact_CityandStateSTR;
if(strlen($CapDeliveryCityANDState) >= 5){ //If more then 5 letters then do the below
$CapDeliveryCityANDState = str_replace('\, ', '\,', ucwords(str_replace('\,', '\, ', strtolower($CapDeliveryCityANDState))));
$CapDeliveryCityANDState = strrev(ucfirst(strrev($CapDeliveryCityANDState)));
if(strpos($CapDeliveryCityANDState, "'")) {
$pos = strpos($CapDeliveryCityANDState, "'") + 1;
$CapDeliveryCityANDState = substr_replace($CapDeliveryCityANDState, strtoupper($CapDeliveryCityANDState[$pos]), $pos, 1);
}
$mystringz = $CapDeliveryCityANDState;
$findmez = ',';
$posz = strpos($mystringz, $findmez);
if ($posz !== false) {
// IF NOT FALSE THEN CAP. LAST 2 LETTERS (STATE)
$CapDeliveryCityANDState[$l=strlen($CapDeliveryCityANDState)-2] = strtoupper($CapDeliveryCityANDState[$l]);
} else {
// ELSE IF FALSE THEN LEAVE AS IS
$CapDeliveryCityANDState = $contact_CityandStateSTR;
}
}
$CapDeliveryCityANDState = str_replace(" ,", ",", $CapDeliveryCityANDState); //remove space after city
$CapDeliveryCityANDState = str_replace(",", ", ", $CapDeliveryCityANDState); //add space after comma
$CapDeliveryCityANDState = preg_replace('!\s+!', ' ', $CapDeliveryCityANDState); //Check and remove double space
Find the apostrophe with strstr(). If it exists, explode the values into the two parts (before and after the apostrophe), capitalize them, then implode() them on the apostrophe again.
Related
This is my string for example:
$x = " i love you/i love her/you love me/you love me "
and i wanted in every blank space to put - so i use:
$y = preg_replace(" ","-",$x);
and i get:
$y = " i-love-you/i-love-her/you-love-me/you-love-me "
in this string i have double expresion YOU LOVE ME, in that case when i have that, i want to add in other not one -, i want to add 2 --
so my final string will look like:
$y = " i-love-you/i-love-her/you-love-me/you--love--me "
Can you help me with these, cause if i use preg replace it will have influence on whole string?
Try This simple code
$x = "i love you/i love her/you love me/you love me";
$strArr = explode("/",$x);
$temp = array();
foreach($strArr as $value){
if(in_array($value,$temp)){
$result[]=str_replace(" ","--",$value);
}else{
$result[]=str_replace(" ","-",$value);
}
$temp[] = $value;
}
echo implode("/",$result);
You can to do it by both ways like regex or non-regex way but this what I got in my mind with array_count_values() and str_replace(). Hope it'll help you :)
<?php
$x = " i love you/i love her/you love me/you love me ";
$sentence = explode('/',trim($x));
$value_counts = array_count_values($sentence);
$expected_result = [];
foreach($value_counts as $k=>$v){
if($v<2){
$expected_result[] = str_replace(' ','-',$k);
}else{
$expected_result[] = str_replace(' ','-',$k);
for($i=2;$i<=$v;$i++){
$expected_result[] = str_replace(' ','--',$k);
}
}
}
echo " ".implode('/', $expected_result)." ";
Output:
i-love-you/i-love-her/you-love-me/you--love--me
DEMO: https://3v4l.org/Hh6Pj
Another more verbose and likely slower method :{
function format_string($x)
{
//trim whitespace to avoid "-" at beginning and end
$x = str_replace(" ","-",trim($x));
// create an array of each entry
$entries = explode("/", $x);
//count each entry
$entry_counts = array_count_values($entries);
foreach($entry_counts as $string => $count){
if($count == 2){
$needs_updating = $string;
}
}
if(isset($needs_updating)){
foreach($entries as $index => &$entry){
if($entry == $needs_updating){
$entries[$index] = str_replace("-", "--",$entry);
}
}
return implode("/", $entries);
}
return implode("/", $entries);
}
Starting with the original string, you can match the slash separated phrases and do the space replacement in a callback function that keeps track of phrases as it goes. If one of the phrases has already appeared, replace the spaces with double dashes instead of single.
$pattern = '/(?<=^|\/).+?(?=\/|$)/';
$phrases = [];
$y = preg_replace_callback($pattern, function($phrase) use (&$phrases) {
$separator = in_array($phrase[0], $phrases) ? '--' : '-';
$phrases[] = $phrase[0];
return str_replace(' ', $separator, $phrase[0]);
}, trim($x));
Here is my go:
$x = " i love you/i love her/you love me/you love me ";
$x = preg_replace_callback('/([^\/]+)\/(\1)?/', function($match){
if(isset($match[2])){
return str_replace(' ', '-', trim($match[1])).'/'.str_replace(' ', '--', trim($match[2]));
}else{
return str_replace(' ', '-', trim($match[1])).'/';
}
}, $x);
echo $x;
Output
i-love-you/i-love-her/you-love-me/you--love--me
And the smallified version of it:
$x = " i love you/i love her/you love me/you love me ";
echo preg_replace_callback('/([^\/]+)\/(\1)?/',function($m){return isset($m[2])?str_replace(' ','-',trim($m[1])).'/'.str_replace(' ','--',trim($m[2])):str_replace(' ','-',trim($m[1])).'/';},$x);
$myvar1 = 'this car is most new and fast';
$myvar2 = explode(' ', $myvar1); // slice on spaces
$myvar3 = implode( ',', $myvar2); //add comman
echo $myvar3;
output = this, car, is, most, new, and, fast
But I need this output = this car, is most, new and, fast
I need in pair output.
Thanks all.
This should do it:
<?php
$str = 'this car is most new and fast';
$str_explode = explode(' ', $str);
$str_result = '';
$comma = false;
foreach($str_explode AS $word) {
$str_result .= $word;
if($comma === false) {
$str_result .= ' ';
$comma = true;
} else {
$str_result .= ', ';
$comma = false;
}
}
echo $str_result;
It uses a boolean that is set to true and false every run so only every other word the comma is shown.
$myvar1 = 'this car is most new and fast';
preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
$myvar1,$myvar2); // splits string on every other space
$myvar3 = implode( ',', $myvar2[0]); //add comman
echo $myvar3;
Instead of explode(), I have used preg_match_all() to split the string and implode() with ','
And here is your output:
this car,is most,new and,fast
I have got a function from Google to clean my paragraph in sentence case.
I want to modify this function such that it converts more than 2 new line character to newline. Else it converts all new line characters in space. So I would have it in paragraph format. Here it's converting all new line character to space.
It's converting in proper sentence case. But, In case If I found single word having first word as capital then I need function to ignore that. As Sometimes, if there would be any noun It needs to be capital. We can't change it small case. Else if noun and it is having more than 2 capital characters other than first character than convert it to lower case.
Like -> Noun => Noun but NoUn => noun. Means I want if other than first character is capital than it convert it two lower case Else it keep it in same format.
function sentence_case($string) {
$sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$new_string = '';
foreach ($sentences as $key => $sentence) {
$new_string .= ($key & 1) == 0?
ucfirst(strtolower(trim($sentence))) :
$sentence.' ';
}
$new_string = preg_replace("/\bi\b/", "I", $new_string);
//$new_string = preg_replace("/\bi\'\b/", "I'", $new_string);
$new_string = clean_spaces($new_string);
$new_string = m_r_e_s($new_string);
return trim($new_string);
}
function sentence_case($str) {
$cap = true;
$ret='';
for($x = 0; $x < strlen($str); $x++){
$letter = substr($str, $x, 1);
if($letter == "." || $letter == "!" || $letter == "?"){
$cap = true;
}elseif($letter != " " && $cap == true){
$letter = strtoupper($letter);
$cap = false;
}
$ret .= $letter;
}
return $ret;
}
This will preserve existing proper noun capitals, acronyms and abbreviations.
This should do it:
function sentence_case($string) {
// Protect the paragraphs and the caps
$parDelim = "/(\n+\r?)/";
$string = preg_replace($parDelim, "#PAR#", $string);
$string = preg_replace("/\b([A-Z])/", "#$1#", $string);
$sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$new_string = '';
foreach ($sentences as $key => $sentence) {
$new_string .= ($key & 1) == 0?
ucfirst(strtolower(trim($sentence))) :
$sentence.' ';
}
$new_string = preg_replace("/\bi\b/", "I", $new_string);
//$new_string = preg_replace("/\bi\'\b/", "I'", $new_string);
$new_string = clean_spaces($new_string);
$new_string = m_r_e_s($new_string);
// Restore the paragraphs and the caps
$new_string = preg_replace("#PAR#", PHP_EOL, $new_string);
$new_string = preg_replace("/#([A-Z])#/", "$1", $new_string);
return trim($new_string);
}
It works by identifying the items you want to protect (paragraph & first cap) and marking it with a string that you can then replace back when you are done. The assumption is that you don't already have #PAR# and #A-Z# in the string. You can use whatever you want to use for the paragraph delimiter afterwards if you want to force a certain type of line ending or several lines in between.
Slightly modifying Sylverdrag's function, I got something that is working well for me. This version works for every messed-up sentence I've thrown at it so far :)
function sentence_case($string) {
$string = strtolower($string); // ADDED THIS LINE
// Protect the paragraphs and the caps
$parDelim = "/(\n+\r?)/";
$string = preg_replace($parDelim, "#PAR#", $string);
$string = preg_replace("/\b([A-Z])/", "#$1#", $string);
$sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$new_string = '';
foreach ($sentences as $key => $sentence) {
$new_string .= ($key & 1) == 0?
ucfirst(strtolower(trim($sentence))) :
$sentence.' ';
}
$new_string = preg_replace("/\bi\b/", "I", $new_string);
// GOT RID OF THESE LINES
// $new_string = preg_replace("/\bi\'\b/", "I'", $new_string);
// $new_string = clean_spaces($new_string);
// $new_string = m_r_e_s($new_string);
// Restore the paragraphs and the caps
$new_string = preg_replace("#PAR#", PHP_EOL, $new_string);
$new_string = preg_replace("/#([A-Z])#/", "$1", $new_string);
$new_string = preg_replace("/#([A-Z])#/", "$1", $new_string);
preg_match('/#(.*?)#/', $new_string, $match); // MODIFIED THIS LINE TO USE (.*?)
return trim($new_string);
}
$string = "that IS it!! YOU and i are Totally DONE hanging out toGether... like FOREveR DUDE! i AM serious. a good FRIEND would NOT treAT me LIKE you dO. it Seems, howEVER, THAT you ARE not ONE of tHe GOOD ONEs.";
echo "<b>String 1:</b> " . $string . "<br><b>String 2:</b> " . sentence_case($string);
PHP Sandbox
:) :)
I have a string in a DB table which is separated by a comma i.e. this,is,the,first,sting
What I would like to do and don't know how is to have the string outputted like:
this, is, the, first and string
Note the spaces and the last comma is replaced by the word 'and'.
This can be your solution:
$str = 'this,is,the,first,string';
$str = str_replace(',', ', ', $str);
echo preg_replace('/(.*),/', '$1 and', $str);
First use, the function provided in this answer: PHP Replace last occurrence of a String in a String?
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos === false)
{
return $subject;
}
else
{
return substr_replace($subject, $replace, $pos, strlen($search));
}
}
Then, you should perform a common str_replace on text to replace all other commas:
$string = str_lreplace(',', 'and ', $string);
str_replace(',',', ',$string);
$words = explode( ',', $string );
$output_string = '';
for( $x = 0; $x < count($words); x++ ){
if( $x == 0 ){
$output = $words[$x];
}else if( $x == (count($words) - 1) ){
$output .= ', and ' . $words[$x];
}else{
$output .= ', ' . $words[$x];
}
}
Well I know obfuscation is a bad idea. But I want all of my html code to come in one long single line. All the html tags are generated through PHP, so I think its possible. I knew replacing \n\r from regular expression, but have no idea how to do this one. In case I am unclear here is an example
$output = '<p>
<div class="title">Hello</div>
</p>';
echo $output;
To be view in the source viewer as <p><div class="title">Hello</div></p>
Maybe this?
$output = str_replace(array("\r\n", "\r"), "\n", $output);
$lines = explode("\n", $output);
$new_lines = array();
foreach ($lines as $i => $line) {
if(!empty($line))
$new_lines[] = trim($line);
}
echo implode($new_lines);
You can try this perhaps.
// Before any output
ob_start();
// End of file
$output = ob_get_clean();
echo preg_replace('/^\s+|\n|\r|\s+$/m', '', $output);
This should, unless I messed up the regex, catch all output, and then replace all new line characters as well as all whitespace at the end and beginning of lines.
If you already have all output collected in a variable, you can of course just use the last line directly and skip the output buffering stuff :)
Worked for me:
$output = str_replace(array("\r\n", "\r", "\n"), "", $output);
You can do :
$output = '<p>'.
'<div class="title">Hello</div>'.
'</p>';
This way, $output won't contain any line jump.
This should also work :
$output = preg_replace(array('/\r/', '/\n/'), '', $output);
$output = preg_replace('!\s+!m', ' ', $output);
This is already well answered, but you may be able to do more than just trim spaces at both ends of each line:
First extract all text within quotes (you don't want to touch those), replace with a marker with a sequence number, store the sequence number with the text
Extract all text within <script></script> tags and do the same as step #1
Replace all white-space (including \n, \r) with spaces
Replace all >1 space sequences with 1 space
Replace all >_< with >< (_ = space)
Replace all _>, <_ and </_ with >, < and </ (_ = space)
Replace markers with the actual texts
This procedure can potentially compact the entire HTML file. This takes advantage of the fact that multiple white-space text inside HTML tags are intepreted as one single space.
This is a (as far as I have tested) working implementation of Stephen Chung's instructions. I'm not entirely convinced by number five, but have included it anyway.
Put the things you want to protect in the protected_parts array. Do it in order that you want them protected. If the starting and ending bits are different (as they would be in HTML tags), separate them by using a comma.
Also, I've no idea if this is the most optimised way of doing this, but it works for me and seems reasonably fast. Feel free to improve, etc. (Let me know if you do too!)
function MinifyHTML($str) {
$protected_parts = array("<pre>,</pre>", "\"", "'");
$extracted_values = array();
$i = 0;
foreach ($protected_parts as $part) {
$finished = false;
$search_offset = 0;
$first_offset = 0;
$startend = explode(",", $part);
if (count($startend) == 1) { $startend[1] = $startend[0]; }
while (!$finished) {
$first_offset = strpos($str, $startend[0], $search_offset);
if ($first_offset === false) { $finished = true; }
else {
$search_offset = strpos($str, $startend[1], $first_offset + strlen($startend[0]));
$extracted_values[$i] = substr($str, $first_offset + strlen($startend[0]), $search_offset - $first_offset - strlen($startend[0]));
$str = substr($str, 0, $first_offset + strlen($startend[0]))."$#".$i."$".substr($str, $search_offset);
$search_offset += strlen($startend[1]) + strlen((string)$i) + 3 - strlen($extracted_values[$i]);
$i++;
}
}
}
$str = preg_replace("/\s/", " ", $str);
$str = preg_replace("/\s{2,}/", " ", $str);
$str = str_replace("> <", "><", $str);
$str = str_replace(" >", ">", $str);
$str = str_replace("< ", "<", $str);
$str = str_replace("</ ", "</", $str);
for ($i = count($extracted_values); $i >= 0; $i--) {
$str = str_replace("$#".$i."$", $extracted_values[$i], $str);
}
return $str;
}
This is an improved function of the above. It adds text area protection and also anything that is a tag remains untouched.
I also removed strlen in the loop (its static).
This might run faster as a one pass filter to check for any of the protected parts. For such a small protected_parts array it's going to be more efficient than looping through the $str four times.
Also this doesn't fix: class = " " (the extra spaces between = and ") as its stuff inside the tags.
function MinifyHTML($str) {
$protected_parts = array('<pre>,</pre>','<textarea>,</textarea>', '<,>');
$extracted_values = array();
$i = 0;
foreach ($protected_parts as $part) {
$finished = false;
$search_offset = $first_offset = 0;
$end_offset = 1;
$startend = explode(',', $part);
if (count($startend) === 1) $startend[1] = $startend[0];
$len0 = strlen($startend[0]); $len1 = strlen($startend[1]);
while ($finished === false) {
$first_offset = strpos($str, $startend[0], $search_offset);
if ($first_offset === false) $finished = true;
else {
$search_offset = strpos($str, $startend[1], $first_offset + $len0);
$extracted_values[$i] = substr($str, $first_offset + $len0, $search_offset - $first_offset - $len0);
$str = substr($str, 0, $first_offset + $len0).'$$#'.$i.'$$'.substr($str, $search_offset);
$search_offset += $len1 + strlen((string)$i) + 5 - strlen($extracted_values[$i]);
++$i;
}
}
}
$str = preg_replace("/\s/", " ", $str);
$str = preg_replace("/\s{2,}/", " ", $str);
$replace = array('> <'=>'><', ' >'=>'>','< '=>'<','</ '=>'</');
$str = str_replace(array_keys($replace), array_values($replace), $str);
for ($d = 0; $d < $i; ++$d)
$str = str_replace('$$#'.$d.'$$', $extracted_values[$d], $str);
return $str;
}
You can't have <div> inside <p> - it is not spec-valid.
If you don't need to store it in a variable you can use this:
?><div><?php
?><div class="title">Hello</div><?php
?></div><?php