Explode and leave delimiter - php

This is my function:
$words = explode('. ',$desc);
$out = '';
foreach ($words as $key => $value) {
$out .= $value;
$rand = rand(0, 4);
if ($rand == 2) {
$out .= "\n";
} else {
$out .= ' ';
}
}
In short it's inserting new lines after random dots, but in this case dots are removed.
How could I do explode('. ',$desc), and leave dots in where they are?

Just put them back in when you concatenate.
$words = explode('. ',$desc);
$out = '';
foreach ($words as $key => $value) {
$out .= $value.'.';
$rand = mt_rand(0, 4);
if ($rand == 2) {
$out .= "\n";
} else {
$out .= ' ';
}
}
You should also use mt_rand(), it is a much better version of rand() unless you like not really random results.

Positive look behind without regex subject.
$words = preg_split('/(?<=\.)(?!\s*$)/', $desc);
Split at any non-character with a dot behind it.

Try this code..
$words = explode('. ',$desc);
$out = '';
foreach ($words as $key => $value) {
$out .= $value;
$rand = rand(0, 4);
if ($rand == 2) {
$out .= "<br>";
} else {
$out .= ' ';
}
}

Related

how to remove string from the end of foreach loop

can I remove the OR from the end of foreach loop
if (isset($_POST['size'])) {
$where .= ' AND ';
$s = $_POST['size'];
$end = count($s);
foreach ($s as $ss) {
$where .= 'pSize=' . $ss;
$where .= ' OR ';
}
} else {
$s = '';
}
with your condition, i think you use IN for easy.
if (isset($_POST['size'])) {
$size = $_POST['size'];
if($size){
$where .= ' AND `pSize` IN ('.implode(",", $size).')';
}
}
this will also work in your case:
if (isset($_POST['size'])) {
$where .= ' AND ';
$s = $_POST['size'];
$end = count($s);
for($i=0;$i<count($s);$i++) {
$where .= 'pSize=' . $s[$i];
if($i != count($s)-1){
$where .= ' OR ';
}
}
} else {
$s = '';
}
One way to avoid that issue is create an array and implode.
if (isset($_POST['size'])) {
$where .= ' AND (';
$s = $_POST['size'];
$end = count($s);
//echo $end;
$aWhere = [];
foreach ($s as $ss) {
$aWhere[] = 'pSize=' . $ss;
}
$where .= implode(' OR ', $aWhere) . ')';
} else {
$s = '';
}
Maybe you need parentheses on the Where, I did it for you.
Take care with SQL injection, use prepared statements.
you can go for many ways
way 1:
you can go for for loop instead of foreach()
$a=sizeof($s);
$x=$a-1;
for($i=0;$i<$a;$i++){
if($i==$x){ $where .= 'pSize=' . $ss;
}
else{ $where .= 'pSize=' . $ss;
$where .= ' OR ';
}
}
way2 : use rtrim()
foreach ($s as $ss) {
$where .= 'pSize=' . $ss;
$where .= ' OR ';
}
$where=rtrim($where,' OR ');
There are many ways to do this. You can even use a for loop. If you'd prefer a foreach loop, you can create an iterator variable to mimic a for loop as follows:
if (isset($_POST['size'])) {
$where .= ' AND ';
$s = $_POST['size'];
$end = count($s);
$i = 0;
foreach ($s as $ss) {
$where .= 'pSize=' . $ss;
if (++$i != $end)
$where .= ' OR ';
}
} else {
$s = '';
}

Function to add HTML tags depending on string content

I have tried to create a function to handle text from the database to be publish with automatic formating.
If there is a \n : it should be converted to <p>...</p>
If there is a - : it should also add the list tags
My problem is that I cant really figure out how to add the <ul> and </ul> tags.
function nl2p($string){
$string = explode("\n", $string);
$paragraphs = '';
foreach ($string as $line) {
if (trim($line)) {
if (substr($line,0,1) == '-'){
$paragraphs .= '<li>' . substr($line,1) . '</li>'."\r\n";
} else {
$paragraphs .= '<p>' . $line . '</p>'."\r\n";
}
}
}
return $paragraphs;
}
Use a variable ($ul in my example):
function nl2p($string){
$string = explode("\n", $string);
$paragraphs = '';
$ul = 0;
foreach ($string as $line) {
if (trim($line)) {
if (substr($line,0,1) == '-'){
if($ul == 0){
$paragraphs .= "<ul>\r\n";
$ul = 1;
}
$paragraphs .= '<li>' . substr($line,1) . '</li>'."\r\n";
} else {
if($ul == 1){
$paragraphs .= "</ul>\r\n";
$ul = 0;
}
$paragraphs .= '<p>' . $line . '</p>'."\r\n";
}
}
}
return $paragraphs;
}
Collect all continuous <li> elements with text in a string and then enclose this string in a <ul> and </ul>.
I would search for the first character to be a dash and, if the previous line did not start with a dash, add the <ul> there. Then wrap the line in li tags and the same check at the end - if the next line does not start with a dash, then add an </ul>.
Then, as a default action, wrap the line in a paragraph.
$string = "this is a string.
New line 1.
New line 2.
- List item
- Another list item
Some more lines of text";
function nl2p($input) {
$lines = explode("\r\n",$input);
$return = '';
foreach($lines as $key => $line) {
if(strpos($line,'-') === 0) {
if(array_key_exists($key-1,$lines) AND strpos($lines[$key-1],'-') === FALSE) {
$return .= '<ul>' . "\r\n";
}
$return .= '<li>' . $line . '</li>' . "\r\n";
if(array_key_exists($key+1,$lines) AND strpos($lines[$key+1],'-') !== 0) {
$return .= '</ul>' . "\r\n";
}
continue;
}
$return .= '<p>' . $line . '</p>' . "\r\n";
}
return $return;
}
var_dump(nl2p($string));
/*
<p>this is a string.</p>
<p>New line 1.</p>
<p>New line 2.</p>
<ul>
<li>- List item</li>
<li>- Another list item</li>
</ul>
<p>Some more lines of text</p>
*/
function nl2p($input) {
if(strpos($input, "\n")) {
$slash = explode("\n",$input);
$newPara = '';
foreach($slash as $slashval) {
$slashval = '#'.$slashval;
if(strpos($slashval,"-")) {
$slashval = substr($slashval, 1);
$hypen = explode("-",$slashval);
$newPara .= '<ul>';
foreach($hypen as $hypenval) {
if(!empty($hypenval)) {
$newPara .= '<li>'.$hypenval.'</li>';
}
}
$newPara .= '</ul>';
} else {
$slashval = substr($slashval, 1);
$newPara .= '<p>'.$slashval.'</p>';
}
}
return $newPara;
} else {
$slashval = $input;
if(strpos($slashval,"-")) {
$hypen = explode("-",$slashval);
$newPara .= '<ul>';
foreach($hypen as $cnt => $hypenval) {
if($cnt == 0) {
$start = $hypenval;
} else {
if(!empty($hypenval)) {
$newPara .= '<li>'.$hypenval.'</li>';
}
}
}
$newPara .= '</ul>';
$newPara = $start.$newPara;
} else {
$slashval = '#'.$input;
if(strpos($slashval,"-")) {
$slashval = substr($slashval, 1);
$hypen = explode("-",$slashval);
$newPara .= '<ul>';
foreach($hypen as $hypenval) {
if(!empty($hypenval)) {
$newPara .= '<li>'.$hypenval.'</li>';
}
}
$newPara .= '</ul>';
}
}
return $newPara;
}
return $input;
}

how can I add items from an array as a class

I am new at php, so please be kind.
I am building a script that gets the number of facebook likes from facebook pages.
Then it sorts them, I have found a way to add the page's profile picture using css, however the only class I am able to add is a url. how can I give each thumbnail it's own class, which I can then apply the css to?
here is my code:
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
function getLikes($arr){
$urls = "";
// Add urls to check for likes
for($i = 0;$i < count($arr);$i++) {
if($urls != "") $urls .= ",https://www.facebook.com/";
$urls .= $arr[$i];
}
// Retreive info from Facebook
$xml = simplexml_load_file("http://api.facebook.com/restserver.php?method=links.getStats&urls=https://www.facebook.com/" . $urls);
$likes = array();
// Loop through the result and populate an array with the likes
for ($i = 0;$i < count($arr);$i++) {
$url = $xml->link_stat[$i]->url;
$counts = (int)$xml->link_stat[$i]->like_count;
$likes[] = array('likes' => $counts,'url' => $url);number_format(1000, 0, '.', ',');
}
return $likes;
}
$array = array("kylieminogue","SiaMusic","iggyazalea");
$likes = getLikes($array);
$likes = array_sort($likes, 'likes', SORT_DESC);
foreach ($likes as $key => $val) {
$final = number_format($val['likes'], 0, '.', ',');
echo "<li class='facebook'><div class='fb-page'><div class='rank'>" . $key . "</div>" . "<div class='thumb " . $val['url'] . "'><div class='link'>" . $val['url'] . "</div></div>" . "<div class='likes'>" . $final . "</div></div></li><br />";
}
If you do this in getLikes(), inside the second loop:
$likes[] = array(
'likes' => $counts,
'url' => $url,
// create a hopefully unique class name
'class' => strtolower($arr[$i]) . '-' . $i
);
// After this you call number_format without receiving its value, why?
Then in the HTML you change
"<div class='thumb " . $val['url'] . "
for
"<div class='thumb " . $val['class'] . "
Is this what you mean?

How to style a character in a string at specific index?

Would you please give me some guidance on how to style one character in a string at specific index? the index of this string comes from an array and in some cases the array is empty, so I only need to style the character in the string if the array is not empty
$indices = array(74, 266);
$string = "CAGGACACTCTTTCTAGTGTTGATTCACCTCGAAGAAGGTCTGGCCTATTAAGAGATCAAGTTCAGTTGGTAAAAAGAAGCAACTCTGCTCGTTATGAGATAGTCCCGATTCAAGATCAACTATCATTTGAGAAGGGTTTCTTTATTGTAATCCGTGCATGCCAGTTGTTGGCTCAGAAGAATGAAGGCATTGTACTGGTGGGAGTCGCTGGTCCTTCAGGGGCCGGAAAGACCATGTTTACAGAAAAGATCCTGAATGTTATGCCTAGTATTGCAATCATAAACATGGACAACTACAATGATCCCAGTCGTATCATTGATGGAAACTTCGACG";
so how do I add a surround the character at the index 74 and 266 with a span so I can give it a different style?
my data is coming from the database so I need to make it dynamic.
Thanks
It's fairly easy: all you need is a few substrs in a loop and to keep track of the character count.
Here's a working code I made:
// zero-based indices
$indices = array(3, 10, 25);
// input
$in = 'abcDefghijKlmnopqrstuvwxyZ';
$openTag = '<b>';
$closeTag = '</b>';
$out = '';
$last = 0;
foreach($indices as $i) {
$fragment = substr($in, $last, $i-$last);
$letter = substr($in, $i, 1);
$last = $i+1;
$out .= $fragment . $openTag . $letter . $closeTag;
}
$out .= substr($in, $last);
// output
echo $out;
For this example, $out is abc<b>D</b>efghij<b>K</b>lmnopqrstuvwxy<b>Z</b>.
For convenience, here's it also as a function:
function highlightChars($text, $indices, $openTag, $closeTag) {
$out = '';
$last = 0;
foreach($indices as $i) {
$fragment = substr($text, $last, $i-$last);
$letter = substr($text, $i, 1);
$last = $i+1;
$out .= $fragment . $openTag . $letter . $closeTag;
}
$out .= substr($text, $last);
return $out;
}

How to wrap words of string every 1000 characters in php

i have some big string, and some array of words that must be replaced with some changes, like wrapping in link. First issue is wrap whole words or combinations words. And the second issue is do previous step minimum every 1000 characters.
$string="lalala word lalala blah, blah lalala combination of words lalala lalala...";
$patterns=array('word','combination of words');
$replacements=array('word','combination of words');
For an example, what i must to do with snippet before?
It sounds to me like you're looking for wordwrap(). You can then use preg_replace_callback() to apply it to your search patterns and make the replacements:
foreach ($patterns as $pattern) {
$regex = '/' . preg_quote($pattern, '/') . '/';
$string = preg_replace_callback($regex, function($match) {
return '<a href="#">'
. wordwrap(htmlspecialchars($match), 1000, '<br />')
. '</a>';
}, $string);
}
SOLUTION:
<?php
function set_keys_by_words($content, $key, $words,$before,$after) {
$positions = array();
$string = '';
for ($i = 0; $i < count($words); $i++) {
$string = preg_replace('/\b' . $words[$i] . '\b/ui', $key . $words[$i], $content);
$position = mb_strpos($string, $key);
if ($position != '') {
$positions[(int) $position] = $words[$i];
}
}
ksort($positions);
$word = '';
$number = '';
$i = 0;
foreach ($positions as $k => $v) {
$i++;
if ($i == 1) {
$number = $k;
$word = $v;
}
}
if ((int) $number) {
$word_len = strlen($word);
$part_after = preg_replace('/\b' . $word . '\b/ui', $before . $word . $after, mb_substr($content, 0, $number + $word_len));
echo $part_after . mb_substr($content, $number + $word_len, 1000);
$content = mb_substr($content, $number + $word_len + 1000);
if ($content != '') {
set_keys_by_words($content, $key, $words);
}
} else if ($number == '' && $content != '') {
echo $content;
}
}
?>

Categories