How do i bold the text in a php str_replace function? - php

<?php
$xml = simplexml_load_file("xmldocumentation.xml")
or die("Error: Cannot create object");
foreach($xml->children() as $pages){
foreach($pages->children() as $page => $data){
echo $data->id;
echo '<br>';
echo $data->timestamp;
//echo $data->revision;
echo "<br />";
echo str_replace("/===[^=]+===/","bold heading here", $data->text);
echo '<p class="text">'.$data->text.'</p>';
}
}
?>
Using php how do i bold the text replaced by php's str_replace function and display the modified content with bold headings ie. ' === Heading === '?
Thanks

Change
echo str_replace("/===[^=]+===/","bold heading here", $data->text);
to
$data->text = preg_replace("/===([^=])+===/","<strong>$1</strong>", $data->text);
You need preg_replace for regex, and need to capture the text you want to bold (via the ()), and then enclose that text in an HTML element that will give you the desired formatting.

A <b> </b> can do the trick!
$strlst = 'lorem ipsum';
$strlst = explode( ' ' , $strlst );
function wrapTag($inVal){
return '<b>'.$inVal.'</b>';
}
$replace = array_map( 'wrapTag' , $strlst );
$Content = str_replace( $strlst , $replace , $Content );
echo $Content;

Related

How to highlight a specific word in a searched content in wordpress

I want to highlight the search term in the content result in WordPress.
I tried some functions for title, excerpt and content highlight. Title and excerpt working fine but in content its not working fine. it disturb my content layout.
My actual layout is
And after using function for highlight search term in content. It looks like this
The function which i use title highlight is
function search_title() {
$title = get_the_title();
$keys = implode('|', explode(' ', get_search_query()));
$content = strip_tags($content);
$title = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $title);
echo $title;
}
And the function which i use for content is
function search_content() {
$content = get_the_content();
$keys = implode('|', explode(' ', get_search_query()));
// $content = strip_tags($content);
$content = preg_replace('/(' . $keys .')/iu', '<strong class="search-highlight">\0</strong>', $content);
$content = preg_replace('~(?:\[/?)[^/\]]+/?\]~s', '', $content);
echo '<p>' . $content . '</p>';
}
Its working fine but break my layout.
I tried some of the jquery methods too. but no luck.
Shaban try this code your search.php and remove search_content() from functions.php
Get the search term by this code.
<?php echo $str = esc_html( get_search_query( false ) ); ?>
and then write jquery in same file with contains: function. like this
$( ".content-column:contains('<?php echo $str ?>')" ).css( "background", "Yellow" );
That's it :)
Hope this will help you

automatic convert word to link in PHP

I want write a simple code that convert special words to special link (for wiki plugin), if it's not a link!
For example suppose we have a text "Hello! How are you?!" and
we want convert are to are, but if we have Hello! How are you?! or Hello! How are you?! does not change. Because it's a link.
How can I do it in PHP?! With preg_replace?! How to?
Thanks.
It's easy.
<?php
$string = "Hello! How are you?!";
$stringTwo = "Hello! how are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "" . $word . "", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)/", $string);
}
echo turnTheWordIntoALink($string, 'are', 'http://google.com');
echo turnTheWordIntoALink($stringTwo, 'are', 'http://google.com');
Output:
First function output: Hello! How are you?!
Second function output: Hello! how are you?!
Alternative:
If you want to not detect <a> tags which were closed, you can use this alternative code:
$stringThree = "Hello! how <a href=\"#\">are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "" . $word . "", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)+(.)+(<\/a>)/", $string);
}
echo turnTheWordIntoALink($stringThree, 'are', 'http://google.com') . "\n";
This gives the output: Hello! how <a href="http://google.com">are you?!
this code is about : if there is a some URL in some phrase it will convert to a link
$word = 'hello how are you google.com, wish you good time';
$prg = "/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($prg, $word, $url))
{
echo preg_replace($prg, "<a href=http://$url[0]>{$url[0]}</a>", $word);
}
else
{
echo $word;
}
To better clarify the issue:
I have a HTML code that have some tags. I want some words in that, converted to some links. But if it is a another link does not convert. See below advanced example for special word you that we want linked to the google:
This is a sample text.
Hello?! How are you?!
Are you ready?!
should be convert to:
This is a sample text.
Hello?! How are you?!
Are you ready ?!
Note that the first you changed, but that second you was not changed, because it's in the another <a> tag.
Answer:
Because of this work has issue with regular expression, this problem can solve without regular expression. Here a simple solution is given:
$data = 'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text.';
$from = " is ";
$to = '<a href="http://www.google.com" > '.$from.' </a>';
echo $data;
$data = explode($from, $data);
echo "<br><br>";
echo $data[0];
$diff = 0;
for($i=1; $i<count($data); $i++){
$n = substr_count($data[$i-1], '<a ') + substr_count($data[$i-1], '<A ');
$m = substr_count($data[$i-1], '</a>') + substr_count($data[$i-1], '</A>');
$diff += $n-$m;
if($diff==0)
echo $to.$data[$i];
else
echo $from.$data[$i];
}

New line to paragraph function

I have this interesting function that I'm using to create new lines into paragraphs. I'm using it instead of the nl2br() function, as it outputs better formatted text.
function nl2p($string, $line_breaks = true, $xml = true) {
$string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);
// It is conceivable that people might still want single line-breaks
// without breaking into a new paragraph.
if ($line_breaks == true)
return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '<br'.($xml == true ? ' /' : '').'>'), trim($string)).'</p>';
else
return '<p>'.preg_replace(
array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
array("</p>\n<p>", "</p>\n<p>", '<br'.($xml == true ? ' /' : '').'>'),
trim($string)).'</p>';
}
The problem is that whenever I try to create a single line break, it inadvertently removes the first character of the paragraph below it. I'm not familiar enough with regex to understand what is causing the problem.
Here is another approach that doesn't use regular expressions. Note, this function will remove any single line-breaks.
function nl2p($string)
{
$paragraphs = '';
foreach (explode("\n", $string) as $line) {
if (trim($line)) {
$paragraphs .= '<p>' . $line . '</p>';
}
}
return $paragraphs;
}
If you only need to do this once in your app and don't want to create a function, it can easily be done inline:
<?php foreach (explode("\n", $string) as $line): ?>
<?php if (trim($line)): ?>
<p><?=$line?></p>
<?php endif ?>
<?php endforeach ?>
The problem is with your match for single line breaks. It matches the last character before the line break and the first after. Then you replace the match with <br>, so you lose those characters as well. You need to keep them in the replacement.
Try this:
function nl2p($string, $line_breaks = true, $xml = true) {
$string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);
// It is conceivable that people might still want single line-breaks
// without breaking into a new paragraph.
if ($line_breaks == true)
return '<p>'.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'), trim($string)).'</p>';
else
return '<p>'.preg_replace(
array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
array("</p>\n<p>", "</p>\n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'),
trim($string)).'</p>';
}
I also wrote a very simple version:
function nl2p($text)
{
return '<p>' . str_replace(['\r\n', '\r', '\n'], '</p><p>', $text) . '</p>';
}
#Laurent's answer wasn't working for me - the else statement was doing what the $line_breaks == true statement should have been doing, and it was making multiple line breaks into <br> tags, which PHP's native nl2br() already does.
Here's what I managed to get working with the expected behavior:
function nl2p( $string, $line_breaks = true, $xml = true ) {
// Remove current tags to avoid double-wrapping.
$string = str_replace( array( '<p>', '</p>', '<br>', '<br />' ), '', $string );
// Default: Use <br> for single line breaks, <p> for multiple line breaks.
if ( $line_breaks == true ) {
$string = '<p>' . preg_replace(
array( "/([\n]{2,})/i", "/([\r\n]{3,})/i", "/([^>])\n([^<])/i" ),
array( "</p>\n<p>", "</p>\n<p>", '$1<br' . ( $xml == true ? ' /' : '' ) . '>$2' ),
trim( $string ) ) . '</p>';
// Use <p> for all line breaks if $line_breaks is set to false.
} else {
$string = '<p>' . preg_replace(
array( "/([\n]{1,})/i", "/([\r]{1,})/i" ),
"</p>\n<p>",
trim( $string ) ) . '</p>';
}
// Remove empty paragraph tags.
$string = str_replace( '<p></p>', '', $string );
// Return string.
return $string;
}
Here's an approach that comes with a reverse method to replace paragraphs back to regular line breaks and vice versa.
These are useful to use when building a form input. When saving a users input you may want to convert line breaks to paragraph tags, however when editing the text in a form, you may not want the user to see any html characters. Then we would replace the paragraphs back to line breaks.
// This function will convert newlines to HTML paragraphs
// without paying attention to HTML tags. Feed it a raw string and it will
// simply return that string sectioned into HTML paragraphs
function nl2p($str) {
$arr=explode("\n",$str);
$out='';
for($i=0;$i<count($arr);$i++) {
if(strlen(trim($arr[$i]))>0)
$out.='<p>'.trim($arr[$i]).'</p>';
}
return $out;
}
// Return paragraph tags back to line breaks
function p2nl($str)
{
$str = preg_replace("/<p[^>]*?>/", "", $str);
$str = str_replace("</p>", "\r\n", $str);
return $str;
}
Expanding upon #NaturalBornCamper's solution:
function nl2p( $text, $class = '' ) {
$string = str_replace( array( "\r\n\r\n", "\n\n" ), '</p><p>', $text);
$string = str_replace( array( "\r\n", "\n" ), '<br />', $string);
return '<p' . ( $class ? ' class="' . $class . '"' : '' ) . '>' . $string . '</p>';
}
This takes care of both double line breaks by converting them to paragraphs, and single line breaks by converting them to <br />
Just type this between your lines:
echo '<br>';
This will give you a new line.

Remove text that is bold in content with Wordpress

I am using the following code below to output content from a category, but the content has bold tags which in turn makes my entire sold bold. What would be easiest way to remove the bold text in my code? Any help would be greatly appreciated, as I am using this to learn.
<p><?php $content = get_the_content();
if (mb_strlen($content) > 700) {
$content = mb_substr($content, 0, 700);
// make sure it ends in a word by chomping at last space
$content = mb_substr($content, 0, mb_strrpos($content, " ")).'...<br /><span class="landing_latest_articles_read_more">Read More</span>';
}
echo $content; ?></p>
strip_tags
or this might work
$string = preg_replace("/<b>|</b>/", "", $string);
Here is a function like strip_tags, only it removes only the tags (with attributes) specified:
<?php
function strip_only($str, $tags) {
if(!is_array($tags)) {
$tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
if(end($tags) == '') array_pop($tags);
}
foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
return $str;
}
?>
so you will use it like this
<p><?php $content = get_the_content();
if (mb_strlen($content) > 700) {
$content = mb_substr($content, 0, 700);
// make sure it ends in a word by chomping at last space
$content = mb_substr($content, 0, mb_strrpos($content, " ")).'...<br /><span class="landing_latest_articles_read_more">Read More</span>';
$content = strip_only($content, '<b>'); //you want to remove <b> tag
}
echo $content; ?></p>
This is working. i tried it here.
If you only wish to remove bold tags:
$content = preg_replace('/<[\/]?b>/i', '', $content);
^
Though you'd have to be sure that it is only <b> tags making things bold and not font tags.

Paragraphs in textarea

I have a form that has a textarea in it. How would I make new lines in the textarea appear as new paragraphs when I echo out the submitted textarea value?
<?php
$textarea = $_POST['textarea'];
$newarr = explode("\n", $textarea);
foreach($newarr as $str) {
echo "<p>".$str."</p>";
}
?>
Use nl2br function:
<?php
echo nl2br($_POST['textarea']);
?>
It will print <br> all newlines
echo '<p>' . preg_replace("~[\r\n]+~", '</p><p>', $textarea) . '</p>';

Categories