How to get the first paragraph bold in the php? - 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));

Related

PHP Form implode / explode

I am using the a db field merchant_sku_item in a form. the original value is separated by / in the db like this:
2*CC689/1*CC368-8/1*SW6228-AB
I want to display in a text area on each line so I tried like this:
<textarea name="merchant_sku_item" rows="5" class="form-control" id="merchant_sku_item"><?
$items=explode('/',$merchant_sku_item);
foreach($items as $item){
echo $item."\r\n";
}
?></textarea>
All works fine:
2*CC689
1*CC368-8
1*SW6228-AB
but when I post the form I get a value like this:
2*CC689 1*CC368-8 1*SW6228-AB
but I wan't it back in the original format to update the DB in the correct format:
2*CC689/1*CC368-8/1*SW6228-AB
I tried to implode it with the / but I think it's just one string now so it's not working. I could replace the spaces I guess but this will not work if the field contains spaces.
Could somebody please tell me the best way to handle this?
The explode is correct, but you cannot just echo $item . "\r\n" because if $item contains </textarea> or whatever HTML you'll skrew up the page. You have to use echo htmlspecialchars($item) . "\n";. Normally, HTML pages have Linux line endings with "\n" and not Windows line endings with "\r\n".
To re-create the value for the DB, you have to take in consideration that the user may add some spaces or new lines. So you might not just get "\r\n" between the values but also " \n" or I don't know what. This is why a regular expression will be more flexible than a simple explode().
The regular expression pattern: \s+
The pattern \s will match any space, tab or new line chars. If you add the + sign after, it means that it can be 1 or multiple times. So this means that " \r\n" will match as it contains spaces, a carriege return and a new line. In PHP, you put the pattern between a delimiter char that you choose and that you put at the begin and the end. Commonly it's a slash so it becomes /\s+/. But you sometimes see also #\s+# or ~\s+~. After this delimiter, you can put some flags to change the way the regular expression is executed. Typically /hello/i will match "Hello" or "hello" because the i flag makes the search case-insensitive.
Similar to what you did: explode and re-implode example:
<?php
// Example of values that could be posted because users are always
// stupid and add spaces that they then don't see anymore.
$examples = [
"2*CC689 1*CC368-8 1*SW6228-AB", // spaces
"2*CC689\n1*CC368-8\n1*SW6228-AB", // new lines
"2*CC689\r\n1*CC368-8\r\n1*SW6228-AB", // carriege returns and new lines
"2*CC689\n 1*CC368-8 \n1*SW6228-AB", // new lines and spaces
];
foreach ($examples as $merchant_sku_item) {
$values = preg_split('/\s+/', $merchant_sku_item);
$merchant_sku_item_for_db = implode('/', $values);
echo $merchant_sku_item_for_db . "\n";
}
?>
Output:
2*CC689/1*CC368-8/1*SW6228-AB
2*CC689/1*CC368-8/1*SW6228-AB
2*CC689/1*CC368-8/1*SW6228-AB
2*CC689/1*CC368-8/1*SW6228-AB
Simplier, you could also just do a replacement with the same regular expression like this:
<?php
// Example of values that could be posted.
$examples = [
"2*CC689 1*CC368-8 1*SW6228-AB", // spaces
"2*CC689\n1*CC368-8\n1*SW6228-AB", // new lines
"2*CC689\r\n1*CC368-8\r\n1*SW6228-AB", // carriege returns and new lines
"2*CC689\n 1*CC368-8 \n1*SW6228-AB", // new lines and spaces
];
foreach ($examples as $merchant_sku_item) {
$merchant_sku_item_for_db = preg_replace('/\s+/', '/', $merchant_sku_item);
echo $merchant_sku_item_for_db . "\n";
}
?>
And just another important point regarding the data the user could input: What happens if the user types "2*CC/689" in the textarea?
Well, this will break your DB value :-/
This means that you have to validate the user input with some checks:
<?php
header('Content-Type: text/plain');
$examples = [
"2*CC689 1*CC368-8 1*SW6228-AB", // spaces
"2*CC689\n1*CC368-8\n1*SW6228-AB", // new lines
"2*CC689\r\n1*CC368-8\r\n1*SW6228-AB", // carriege returns and new lines
"2*CC689\n 1*CC368-8 \n1*SW6228-AB", // new lines and spaces
// Test with invalid datas:
"2*C/C689\n1*CC368-8\n1*SW6228-AB", // slash not allowed
"*CC689\n1*CC368-8\n1*SW6228-AB", // missing number before the *
"1*\n1*CC368-8\n1*SW62?28-AB", // missing product identifier and invalid ?
"1CC689 1*CC368-8 1SW6228-AB", // missing *
];
foreach ($examples as $example_nbr => $merchant_sku_item) {
echo str_repeat('=', 80) . "\n";
echo "Example $example_nbr\n\$merchant_sku_item = \"$merchant_sku_item\"\n";
$values = preg_split('/\s+/', $merchant_sku_item);
$errors = [];
foreach ($values as $i => $value) {
echo "Value $i = \"$value\"";
// Pattern: a number followed by * and followed by a product id (length between 3 and 10).
if (!preg_match('/^\d+\*[\d\w-]{3,10}$/i', $value)) {
echo " <-- ERROR\n";
$errors[] = $value;
} else {
echo "\n"; // It's ok
}
}
if (!empty($errors)) {
// You should handle the error and reload the form with the posted value and an error
// message explaining to the user what format is allowed.
echo "ERROR: Cannot save the value because the following products are wrong:\n";
echo implode("\n", $errors) . "\n";
}
}
?>
Test it here: https://onecompiler.com/php/3xtff6nk8
You can use preg_replace for your final post string like below code
$str = "2*CC689 blue 1*CC368-8 red 1*SW6228-AB";
$items = preg_replace('/\s+/', '/', $str);
echo $items;
output
2*CC689/blue/1*CC368-8/red/1*SW6228-AB
I Hope understand your question exactly.
Try replacing the created spaces and removing newline characters like so:
<?php
$merchant_sku_item = str_replace("\r\n","/",trim($_POST["merchant_sku_item"]));
?>
Make it this way:
<textarea name="merchant_sku_item" rows="5" class="form-control" id="merchant_sku_item"><?
$items=explode('//',$merchant_sku_item);
foreach($items as $item){
echo $item."\r\n";
}
?></textarea>

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.

Why every '<~~~>' is not replacing with color name? Why only last one is working?

<?php
$color='red';
$lines=file("new.txt");
foreach ($lines as $line) {
if($line=='<~~~>'){
if($color=='red')
echo $color='yellow';
elseif($color=='yellow')
echo $color='red';
}
else{
echo $line."<br>";
}
}
?>
File Content:
hey there how are you
<~~~>
I am fine What about you?
<~~~>
I am also good. thank you.
<~~~>
Output is coming:
hey there how are you
<~~~>
I am fine What about you?
<~~~>
I am also good. thank you.
yellow
There's a trailing newline char at the end of each line. Use trim($line) to get rid of it :
<?php
$color = 'red';
$lines = file("new.txt");
foreach ($lines as $line) {
if (trim($line) == '<~~~>') {
if ($color == 'red')
echo $color = 'yellow';
else if ($color == 'yellow')
echo $color = 'red';
echo "<br />"; // Added to keep the original format
} else {
echo $line . "<br />";
}
}
Output :
hey there how are you
yellow
I am fine What about you?
red
I am also good. thank you.
yellow
It is explained in the documentation of PHP file() function:
Return Values
Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached.
This means, except for the last line, in case it doesn't end with a new line character, no line in your file can be equal to string '<~~~>'.
The solution(s) are also provided in the same documentation page, one paragraph below:
Note:
Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.
Your problem is
echo $color='yellow';
just do
echo 'yellow'
instead. Same goes for the echo 'red'
The expression "$color = 'yellow'" produces a return value of 'void' which then is seen by the "echo". So actually you're doing a "echo void;" equivalent.

How can I separate a string of urls and print each link?

How can I separate each link from my string:
$field = "www.link1.com
www.link2.com";
And output them like this (expected output):
link1 title
www.link1.com
link2 title
www.link2.com
My current code looks like this:
<?php
$field =
"www.link1.com
www.link2.com";
if ($field == "link1");
{
$output="link1 title</br>".$field ;
}
echo $output;
?>
But it only outputs this (current output):
link1 title
www.link1.com www.link2.com
So how can I change/modify my code to get the urls separated and print them like shown above?
This should work for you:
Here I first explode() your string into an array, so that we have each url as array element.
Then we just loop through each link and print them. We also grab the name between www. and the next dot with preg_replace().
$arr = array_map("trim", explode(PHP_EOL, $field));
foreach($arr as $v) {
echo $v . " title<br>";
echo preg_replace("/^www\.([^\.]*)(.*?)$/", "$1", $v) . "<br><br>";
}

Remove Text With Preg_Replace

I have some text like the following example:
Some Text Here
[code]Some link[/code]
Text
[code]Link[/code]
Other Text
[code]Another Link[/code]
Other Text1
I want to remove all the text above, under, and between the two code. Here's an example of the output I want:
[code]Some Link[/code]
[code]Link[/code]
[code]Another Link[/code]
I use preg_replace for removing text above the first Code, in this way:
$message = preg_replace('/(.*?)\[code/si','[code',$message, 1);
Can you help me to remove the other text, using preg_replace?
You can do this way:
preg_match_all('/(\[code\].*\[\/code\])/Usmi', $text, $res);
$cnt = 0;
foreach ($res as $val) {
$cnt++;
$message .= $val[$cnt] . "<br />";
}
echo $message;
Just to make the solution of #Andreev a little more simple :
$text = "
Some Text Here
[code]Some link[/code]
Text
[code]Link[/code]
Other Text
[code]Another Link[/code]
Other Text1
";
$keywords = preg_match_all('/(\[code\].*\[\/code\])/Usmi', $text, $res);
print(implode($res[0]));
You can test it here : http://phptester.net/index.php?lang=en
Assuming you can never have [code] abc [code] def [/code] ghi [/code], try this:
do {
$message = preg_replace("((?:\[code\].*?\[/code\])*).*?(?=\[code\]))is","$1",$message,-1,$c);
} while($c);

Categories