How to explode a string, with spaces and new lines? - php

I would like to explode a string (separated based on a delimiter and placed into an array), using both a space (" ") and a newline ("\n") as a delimiter.
The method (which I don't think is the best way) is to:
Explode the array by spaces
Remake the string from the array
Explode it again for new lines
MySQL escape the individual elements.
Question: How do I exploded a string by both a space and new line?
Reference to: new line Array

You could just do a
$segments = preg_split('/[\s]+/', $string);
This function will split $string at every whitespace (\s) occurrence, including spaces, tabs and newlines. Multiple sequential white spaces will count as one (e.g. "hello, \n\t \n\nworld!" will be split in hello, and world! only, without empty strings in the middle.
See function reference here.

You can use preg_split to explode the content using multiple delimiter
$pattern = '/[ \n]/';
$string = "something here ; and there, oh,that's all!";
echo '<pre>', print_r( preg_split( $pattern, $string ), 1 ), '</pre>';

Always go from the bigger to the smaller one.
So first split by "\n" and then split by " ".
$data = "This is a test\nAnd something new happens.";
$rows = explode("\n", $data);
$words = array();
foreach($rows as $row) {
$temp = explode(" ", $row);
foreach($temp as $word)
$words[] = $word;
}
Will give you an array with all words in it.

You can use to explode the content using multiple delimiter.
Sample code
<?php
$str = "Brand : Pandora~ Collection : Summer 13~ Colour : Multi~ Gender : Ladies~ Material : Murano Glass~ Our Code : 0573835~ Packaging : Pandora Branded Packaging~ Product Code : 750513~ Product Type : Bead~ Style : Contemporary";
$r1 = explode("~", $str);
$stringtxt = '<table>';
if (count($r1) > 0) {
foreach ($r1 as $value) {
$rows = explode(":", $value);
$stringtxt .= '<tr>';
$stringtxt .= '<td>' . $rows[0] . '</td><td>' . $rows[1] . '</td>';
$stringtxt .= '</tr>';
}
}
$stringtxt .= '</table>';
print $stringtxt;
?>
Output
<table>
<tr><td>Brand </td><td> Pandora</td></tr>
<tr><td> Collection </td><td> Summer 13</td></tr>
<tr><td> Colour </td><td> Multi</td></tr>
<tr><td> Gender </td><td> Ladies</td></tr>
<tr><td> Material </td><td> Murano Glass</td></tr>
<tr><td> Our Code </td><td> 0573835</td></tr>
<tr><td> Packaging </td><td> Pandora Branded Packaging</td></tr>
<tr><td> Product Code </td><td> 750513</td></tr>
<tr><td> Product Type </td><td> Bead</td></tr>
<tr><td> Style </td><td> Contemporary</td></tr>
</table>

Related

Count Number Of Words In a Textarea

I have a text area that gets input from a PHP script, and I would like to count the number of words or line breaks in the textarea and echo it below the text area.
This is what the code looks like for the textarea.
<textarea name="domains" cols="120" rows="5" style="max-width:100%;">
<?php $output_array = explode(" ",$output);
$count = count($output_array);
for ($i=0;$i<$count;$i++){
echo $output_array[$i]."\n";
}
?>
</textarea><br />
<br>
<?php
preg_match_all("/(\n)/", $_POST['domains'], $matches);
$total_lines = count($matches[0]) + 1;
echo $total_lines;
?>
<br />
I tried using preg_match_all but the output I get is only "1", regardless of how many line breaks are inside the text area.
$str = 'as aa frd sad as
kjhsdf sdkjh
sd sdkjhsdf
sjkldhfh sdfjh sd';
preg_match_all("/\w+/", $str, $matches);
echo 'Words = ' . count($matches[0]);
echo PHP_EOL;
preg_match_all("/\n/", $str, $matches);
echo 'newlines = ' . count($matches[0]);
echo PHP_EOL;
echo 'So number of line is = ' . count($matches[0])+1;
RESULT
Words = 12
newlines = 3
So number of line is = 4
You can do the following:
$arr = array_filter(explode(" ", $input) function($item) {
return !!$item;
});
$count = count($arr) + count(explode("\n", implode(",", $arr)));
This splits the string by space, filters out empty items to avoid issues due to multiple spaces found between words, then glues the array back into a string, splits it by newline and adds the two counts together.

separate each words in php

I had an value in database like "demo text" . I want to display this content from the db in the view page as
Html code that i am using is like this <h2>Demo<span>Text</span></h2> , is there any solution for seperate each words and use one for h2 and other for span. I am using php codeigniter for the project , I don't know that whether the way i explained my problem is correct or not .
Yes you can so it with explode
if you have stored at least 2 words with space. try following
$demo ="demo text";
$arr = explode(" ",$demo);
$str = "<h2>".$arr[0]."<span>".$arr[1]."</span></h2>";
echo $str;
DEMO
EDIT
If you have more words and want to split first word only you can pass limit parameter in explode
$demo ="Pligrimage to Marian Shrines";
$arr = explode(" ",$demo,2);
$str = "<h2>".$arr[0]."<span>".$arr[1]."</span></h2>";
echo $str;
DEMO
I think you are looking for something like this!
$your_string = "Hello Houston! We have a problem!";
$my_array = explode(" ",trim($your_string));
$output = "<h2>";
foreach($my_array as $a_word){
if ($a_word === reset($my_array))
$output .= $a_word;
else
$output .= " <span>". $a_word . "</span>";
}
$output .= "</h2>";
print $output;

Replace mysql result's one row's spaces into '-'

while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo " {$row['id']}. ". "{$row['name']} <br> ".
"Music : {$row['lljhg2']} <br> ".
"Video : {$row['description']} <br> ".
"Song : {$row['artist']} <br> ".
"--------------------------------<br>";}
Some code Like this, I want {$row['name']} in <a href=\"/load/{$row['id']}/{$row['name']}\"> I want this row results all spaces replaced by dash ('-').
If the result is:
Prince Reoy from USA
I want to print this:
prince-reoy-from-usa
Is it possible?
either use this query
select lcase(replace(name, ' ', '-')) from table_name
or this php code
strtolower(' ', '-', str_replace($row['name']))
This will replace spaces with dashes, and make the whole string lower case:
strtolower(str_replace(' ', '-', $row['name']))
You can use implode() which will add the "glue" (the '-') between pieces of the array to make a string. Then you can lower the case of the string all at once with strtolower():
$row_data = strtolower(implode('-', $row));
echo $row_data;

How to get the first paragraph bold in the php?

I am entering text in the database in two paragraphs
first paragraph
second paragraph
I am storing them in my database and when I am displaying them on the frontend using nl2br it is getting displayed perfectly.
I want the my first paragraph to be bold and the second paragraph should be normal.
I tried using strpos to find the location of the <br> tag after nl2br to chop off the first paragraph but I am not succeeding.
the failed code is
echo strpos(nl2br($row['article']), "<br>");
but i am not getting the position of the <br> tag
I got the correct answer from eddie, he deleted it but i am updating the answer here
$str='first paragraph
second paragraph';
foreach(explode("\n",) as $key => $val) {
if($key == 0){
echo'<b>';
}
echo $val;
echo'<br>';
if($key == 0){
echo '</b>';
}
}
Don’t use nl2br for the type of results you are looking for. Just split the string into an array using a regex rule with preg_split and then act on the first item in the array. Here is test code:
// Set the test data.
$test_data = <<<EOT
first paragraph
second paragraph
EOT;
// Split the test data into an array of lines.
$line_array = preg_split('/(\r?\n){1,2}/', $test_data);
// Roll through the line array & act on the first line.
$final_text = '';
foreach ($line_array as $line_key => $line_value) {
if ($line_key == 0) {
$line_value = "<b>" . $line_value . "</b>";
}
$final_text .= $line_value . "<br />\n";
}
// Dump the line array for debugging.
echo '<pre>';
print_r($line_array);
echo '</pre>';
// Echo the final text.
echo '<pre>';
echo htmlentities($final_text);
echo '</pre>';
die();
The output from the dump of the line array would be this:
Array
(
[0] => first paragraph
[1] => second paragraph
)
And the test output using htmlentities to show what was done HTML-wise:
<b>first paragraph</b><br />
second paragraph<br />
Try:
$first_line = explode(PHP_EOL, $str)[0];
$new_str = str_replace($first_line,'<b>'.$first_line.'</b>',nl2br($str));

Replace text ignoring HTML tags

I have a simple text with HTML tags, for example:
Once <u>the</u> activity reaches the resumed state, you can freely add and remove fragments to the activity. Thus, <i>only</i> while the activity is in the resumed state can the <b>lifecycle</b> of a <hr/> fragment change independently.
I need to replace some parts of this text ignoring its html tags when I do this replace, for example this string - Thus, <i>only</i> while I need to replace with my string Hello, <i>its only</i> while . Text and strings to be replaced are dynamically. I need your help with my preg_replace pattern
$text = '<b>Some html</b> tags with <u>and</u> there are a lot of tags <i>in</i> this text';
$arrayKeys= array('Some html' => 'My html', 'and there' => 'is there', 'in this text' => 'in this code');
foreach ($arrayKeys as $key => $value)
$text = preg_replace('...$key...', '...$value...', $text);
echo $text; // output should be: <b>My html</b> tags with <u>is</u> there are a lot of tags <i>in</i> this code';
Please help me to find solution. Thank you
Basically we're going to build dynamic arrays of matches and patterns off of plain text using Regex. This code only matches what was originally asked for, but you should be able to get an idea of how to edit the code from the way I've spelled it all out. We're catching either an open or a close tag and white space as a passthru variable and replacing the text around it. This is setup based on two and three word combinations.
<?php
$text = '<b>Some html</b> tags with <u>and</u> there are a lot of tags <i>in</i> this text';
$arrayKeys= array(
'Some html' => 'My html',
'and there' => 'is there',
'in this text' =>'in this code');
function make_pattern($string){
$patterns = array(
'!(\w+)!i',
'#^#',
'! !',
'#$#');
$replacements = array(
"($1)",
'!',
//This next line is where we capture the possible tag or
//whitespace so we can ignore it and pass it through.
'(\s?<?/?[^>]*>?\s?)',
'!i');
$new_string = preg_replace($patterns,$replacements,$string);
return $new_string;
}
function make_replacement($replacement){
$patterns = array(
'!^(\w+)(\s+)(\w+)(\s+)(\w+)$!',
'!^(\w+)(\s+)(\w+)$!');
$replacements = array(
'$1\$2$3\$4$5',
'$1\$2$3');
$new_replacement = preg_replace($patterns,$replacements,$replacement);
return $new_replacement;
}
foreach ($arrayKeys as $key => $value){
$new_Patterns[] = make_pattern($key);
$new_Replacements[] = make_replacement($value);
}
//For debugging
//print_r($new_Patterns);
//print_r($new_Replacements);
$new_text = preg_replace($new_Patterns,$new_Replacements,$text);
echo $new_text."\n";
echo $text;
?>
Output
<b>My html</b> tags with <u>is</u> there are a lot of tags <i>in</i> this code
<b>Some html</b> tags with <u>and</u> there are a lot of tags <i>in</i> this text
Here we go. this piece of code should work, assuming you're respecting only twp constraints :
Pattern and replacement must have the same number of words. (Logical, since you want to keep position)
You must not split a word around a tag. (<b>Hel</b>lo World won't work.)
But if these are respected, this should work just fine !
<?php
// Splits a string in parts delimited with the sequence.
// '<b>Hey</b> you' becomes '~-=<b>~-=Hey~-=</b>~-= you' that make us get
// array ("<b>", "Hey" " you")
function getTextArray ($text, $special) {
$text = preg_replace ('#(<.*>)#isU', $special . '$1' . $special, $text); // Adding spaces to make explode work fine.
return preg_split ('#' . $special . '#', $text, -1, PREG_SPLIT_NO_EMPTY);
}
$text = "
<html>
<div>
<p>
<b>Hey</b> you ! No, you don't have <em>to</em> go!
</p>
</div>
</html>";
$replacement = array (
"Hey you" => "Bye me",
"have to" => "need to",
"to go" => "to run");
// This is a special sequence that you must be sure to find nowhere in your code. It is used to split sequences, and will disappear.
$special = '~-=';
$text_array = getTextArray ($text, $special);
// $restore is the array that will finally contain the result.
// Now we're only storing the tags.
// We'll be story the text later.
//
// $clean_text is the text without the tags, but with the special sequence instead.
$restore = array ();
for ($i = 0; $i < sizeof ($text_array); $i++) {
$str = $text_array[$i];
if (preg_match('#<.+>#', $str)) {
$restore[$i] = $str;
$clean_text .= $special;
}
else {
$clean_text .= $str;
}
}
// Here comes the tricky part.
// We wanna keep the position of each part of the text so the tags don't
// move after.
// So we're making the regex look like (~-=)*Hey(~-=)* you(~-=)*
// And the replacement look like $1Bye$2 me $3.
// So that we keep the separators at the right place.
foreach ($replacement as $regex => $newstr) {
$regex_array = explode (' ', $regex);
$regex = '(' . $special . '*)' . implode ('(' . $special . '*) ', $regex_array) . '(' . $special . '*)';
$newstr_array = explode (' ', $newstr);
$newstr = "$1";
for ($i = 0; $i < count ($regex_array) - 1; $i++) {
$newstr .= $newstr_array[$i] . '$' . ($i + 2) . ' ';
}
$newstr .= $newstr_array[count($regex_array) - 1] . '$' . (count ($regex_array) + 1);
$clean_text = preg_replace ('#' . $regex . '#isU', $newstr, $clean_text);
}
// Here we re-split one last time.
$clean_text_array = preg_split ('#' . $special . '#', $clean_text, -1, PREG_SPLIT_NO_EMPTY);
// And we merge with $restore.
for ($i = 0, $j = 0; $i < count ($text_array); $i++) {
if (!isset($restore[$i])) {
$restore[$i] = $clean_text_array[$j];
$j++;
}
}
// Now we reorder everything, and make it go back to a string.
ksort ($restore);
$result = implode ($restore);
echo $result;
?>
Will output Bye me ! No, you don't need to run!
[EDIT] Now supporting a custom pattern, which allows to avoid adding useless spaces.

Categories