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);
Related
I need to edit all odd words to upper case.
Here is sample of imput string:
very long string with many words
Expected output:
VERY long STRING with MANY words
I have this code, but it seams to me, that I can do it in better way.
<?php
$lines = file($_FILES["fname"]["tmp_name"]);
$pattern = "/(\S[\w]*)/";
foreach($lines as $value)
{
$words = NULL;
$fin_str = NULL;
preg_match_all($pattern, $value, $matches);
for($i = 0; $i < count($matches[0]); $i = $i + 2){
$matches[0][$i] = strtoupper($matches[0][$i]);
$fin_str = implode(" ", $matches[0]);
}
echo $fin_str ."<br>";
P.S. I need to use only preg_match function.
Here's a preg_replace_callback example:
<?php
$str = 'very long string with many words';
$newStr = preg_replace_callback('/([^ ]+) +([^ ]+)/',
function($matches) {
return strtoupper($matches[1]) . ' ' . $matches[2];
}, $str);
print $newStr;
// VERY long STRING with MANY words
?>
You only need to match the repeating pattern: /([^ ]+) +([^ ]+)/, a pair of words, then preg_replace_callback recurses over the string until all possible matches are matched and replaced. preg_replace_callback is necessary to call the strtoupper function and pass the captured backreference to it.
Demo
If you have to use regular expressions, this should get you started:
$input = 'very long string with many words';
if (preg_match_all('/\s*(\S+)\s*(\S+)/', $input, $matches)) {
$words = array();
foreach ($matches[1] as $key => $odd) {
$even = isset($matches[2][$key]) ? $matches[2][$key] : null;
$words[] = strtoupper($odd);
if ($even) {
$words[] = $even;
}
}
echo implode(' ', $words);
}
This will output:
VERY long STRING with MANY words
You may don't need regex simply use explode and concatenate the string again:
<?php
function upperizeEvenWords($str){
$out = "";
$arr = explode(' ', $str);
for ($i = 0; $i < count($arr); $i++){
if (!($i%2)){
$out .= strtoupper($arr[$i])." ";
}
else{
$out .= $arr[$i]." ";
}
}
return trim($out);
}
$str = "very long string with many words";
echo upperizeEvenWords($str);
Checkout this DEMO
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
I want to know how to count to the second space then return to the newline with php , for example :
the text: "How are you?"
becomes
"how are
you?"
how can I do that with php?
thank you
Here is a function that uses strpos to return the position of the Nth specified character.
http://us2.php.net/manual/en/function.strpos.php#96576
Find that position, then do a substr_replace to put a \n in that spot.
print preg_replace('/((:?\S+\s){2})/i', "\$1\r\n", "How are you?" );
function addNlToText($text) {
$words = explode(' ', $text);
$out = '';
foreach ($words as $key => $value) {
$out .= $value;
if ($key % 2 === 0) {
$out .= "\n";
} else {
$out .= ' ';
}
}
return trim($out);
}
That's dirty, but it does what you ask...
$text = 'Hello, how are you?';
addNlToText($text); // "Hello, how\nare you?"
$text = 'Hello';
addNlToText($text); // "Hello"
$text = 'Hello what is going on?';
addNlToText($text); // "Hello what\nis going\non?"
I wonder if you are not after something like the wordwrap function?
http://www.php.net/wordwrap
Try this:
<?php
$mystring = 'How are you?';
$findme = ' ';
$pos = strpos($mystring, $findme);
$pos = strpos($mystring, $findme, $pos+1);
$mystring = substr_replace($mystring, '<br>', $pos, 0);
echo $mystring;
?>
You can do it using javascript, Is it ok using javascript?
i have string like this
$string = 'aaaaaa, bbbbbb, cccccc, ';
and i want to modified it to be like this
$string = 'aaaaaa, bbbbbb, cccccc';
the last ',' and space is removed.
how to do this in php?
what is the function needed the achieve that?
my full code is like this
if(isset($_POST['accomodation'])) $accomodation = 'Accomodation, ';
if(isset($_POST['dance'])) $dance = 'Dance Lessons, ';
if(isset($_POST['vacation'])) $vacation = 'Vacation planning, ';
if(isset($_POST['group'])) $group = 'Group Vacation, ';
if(isset($_POST['inprivate'])) $inprivate = 'Private Vacation, ';
if(isset($_POST['land'])) $land = 'Land purchase/lease';
if(isset($_POST['all'])) $all = 'All';
#$interest = $accomodation.$dance.$vacation.$group.$inprivate.$land;
#echo $string;
*sorry for such dumb question, it's been so long i didn't touch native PHP programming
rtrim() function:
rtrim($string,', ');
but how are you defining the string? It may be that you can build it without the comma and space.
EDIT
$interests = array();
if(isset($_POST['accomodation'])) $interests[] = 'Accomodation';
if(isset($_POST['dance'])) $interests[] = 'Dance Lessons';
if(isset($_POST['vacation'])) $interests[] = 'Vacation planning';
if(isset($_POST['group'])) $interests[] = 'Group Vacation';
if(isset($_POST['inprivate'])) $interests[] = 'Private Vacation';
if(isset($_POST['land'])) $interests[] = 'Land purchase/lease';
if(isset($_POST['all'])) $all = 'All';
$interest = implode(', ',$interests);
echo $interest;
$string = preg_replace('/\s*,\s*$/', '', $string);
or, way cooler:
$string = rtrim($string, " ,");
Note that it does not matter the order of the characters in the pattern string.
#You last update.
This changes some things. You could put all your variables in one array and then implode it. Like so:
$items = array();
$items[] = $accomodation = 'Accomodation';
$items[] = $dance = 'Accomodation';
...
$result = implode(', ', $items)
$string = preg_replace( "/,\s*$/","",$string);
Should do the trick
Is it always a comma then a space at the end?
substr($string, 0, -2)
Often times, you can avoid the trailing comma altogether by changing the way you build the string. For example:
$count = 0;
foreach ($this as $that) {
if ($count != 0) {
$string .= ',';
}
$string .= $that['stuff'];
$count++;
}
Would remove the possibility of any trailing comma at the end, no matter the combination of results.
i need the following -
if i have a sentence
$str = "i like programming very much";
and i search for a word
$word = "r";
i expect it to return the sentence
"i like *p***r***og***r***aming* *ve***r***y* much"
I wrote the following regex for it, but it sometimes doesn't work.
$str = preg_replace("/([^\s{".preg_quote($word)."}]*?)(".preg_quote($word).")([^\s{".preg_quote($word)."}]*)/siu","<span class='pice1'>$1</span><span class='pice2'>$2</span><span class='pice1'>$3</span>",$str);
Could you tell me what i wrote wrong?
Thanks
UPDATE:
for example it doesn't work when
$str = "ameriabank"; and $word = "ab";
...
Why dont't you just use str_replace()? I think it's more simple
$search = "ab";
$word = "ameriabank";
$newstr = "<span class=\"pice1\">".str_replace($search, $word, "</span><span class=\"pice3\">".$search."</span></span class=\"pice1>\")."</span>";
$str = "i like programming very much";
$w = "r";
echo preg_replace("/($w)/", "<b>$1</b>", $str);
Output:
i like p<b>r</b>og<b>r</b>amming ve<b>r</b>y much
Answer to the comment: do it in two steps.
$str = "i like programming very much ready tear";
$w = "r";
$str = preg_replace("/\\b((?:\\w+|\\b)$w(\\w+|\\b))\\b/", "<i>$1</i>", $str);
$str = preg_replace("/($w)/", "<b>$1</b>", $str);
echo $str;
output:
i like <i>p<b>r</b>og<b>r</b>amming</i> <i>ve<b>r</b>y</i> much <i><b>r</b>eady</i> <i>tea<b>r</b></i>
visit highlight multiple keywords in search and be amazed.
What about this way :
$str = "i like programming very much";
$word = "r";
$list = explode(' ',$str);
for($i=0; $i<count($list); $i++) {
if(preg_match("/$word/", $list[$i])) {
$list[$i] = '<i>'.preg_replace("/$word/siu", "<b>$word</b>", $list[$i]).'</i>';
}
}
$str = implode(' ',$list);
echo $str,"\n";
$str = "i like programming very much";
$word = "r";
function highlight($matches)
{
global $word;
return '<span class="pice1">'.str_replace($word,'<span class="pice2">'.$word.'</span>',$matches[0]).'</span>';
}
echo $str = preg_replace_callback("/([^\s]*?".preg_quote($word, '/')."[^\s]*)/siu", highlight, $str);
do the job(and it works with foreign languages too)...