Remove new line in wysiwyg redactor - php

I'm using the wysiwyg in the back end and use the following code to limit the string, "...read more" will be displayed at the end of the sentence.
function limit_words($string)
{
$word_limit = '60';
$words = explode(" ",$string);
return implode(" ",array_splice($words,0,$word_limit));
}
<?php echo limit_words($rows['content']); ?>... read more
Here is my problem. The "...read more" is showing properly when the string characters are more than 60.
But if the string characters are less than 60, the read more text is showing in new line. I know this is causing by <p>, which is auto generate from wysiwyg.
Is it possible to solve this issue on this section only?

Solved by using regular expression to remove <p> tags around elements
$replaced = preg_replace('~</?p[^>]*>~', ' ', $rows['content']);
echo limit_words($replaced); ?>... read more

Related

PHP preg_replace: Replace all anchor tags in text with their href value with Regex

I want to replace all anchor tags within a text with their href value, but my pattern does not work right.
$str = 'This is a text with multiple anchor tags. This is the first one: Link 1 and this one the second: Link 2 after that a lot of other text. And here the 3rd one: Link 3 Some other text.';
$test = preg_replace("/<a\s.+href=['|\"]([^\"\']*)['|\"].*>[^<]*<\/a>/i",'\1', $str);
echo $test;
At the end the text should look like this:
This is a text with multiple anchor tags. This is the first one: https://www.link1.com/ and this one the second: https://www.link2.com/ after that a lot of other text. And here the 3rd one: https://www.link3.com/ Some other text.
Thank you very much!
Just don't.
Use a parser instead.
$dom = new DOMDocument();
// since you have a fragment, wrap it in a <body>
$dom->loadHTML("<body>".$str."</body>");
$links = $dom->getElementsByTagName("a");
while($link = $links[0]) {
$link->parentNode->insertBefore(new DOMText($link->getAttribute("href")),$link);
$link->parentNode->removeChild($link);
}
$result = $dom->saveHTML($dom->getElementsByTagName("body")[0]);
// remove <body>..</body> wrapper
$output = substr($result, strlen("<body>"), -strlen("</body>"));
Demo on 3v4l
In case you're still set on regex, this should work:
preg_replace("/<a\s+href=['\"]([^'\"]+)['\"][^\>]*>[^<]+<\/a>/i",'$1', $str);
But you're probably better off with a solution like what Andreas posted.
FYI: the reason your previous regex didn't work was this little number:
.*>
Because . selects everything you ended up matching everything past the url to be replaced; all the way to the end. This is why it appeared to only select and replace the first anchor tag it found and cut off the rest.
Changing that to
[^\>]*
Ensures that this particular selection is constrained to only the portion of the string which exists between the url and the ending bracket of the a tag.
Simpler perhaps not, but safer is to loop the string with strpos to find and cut the string and remove the html.
$str = 'This is a text with multiple anchor tags. This is the first one: <a class="funky-style" href="https://www.link1.com/" title="Link 1">Link 1</a> and this one the second: Link 2 after that a lot of other text. And here the 3rd one: Link 3 Some other text.';
$pos = strpos($str, '<a');
while($pos !== false){
// Find start of html and remove up to link (<a href=")
$str = substr($str, 0, $pos) . substr($str, strpos($str, 'href="', $pos)+6);
// Find end of link and remove that.(" title="Link 1">Link 1</a>)
$str = substr($str, 0, strpos($str,'"', $pos)) . substr($str, strpos($str, '</a>', $pos)+4);
// Find next link if possible
$pos = strpos($str, '<a');
}
echo $str;
https://3v4l.org/vdN7E
Edited to handle different order of a a-tag.
If you want to replace a tags with href values you can do:
$post = preg_replace("/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/","$1",$post);
If you want to replace with text values:
$post = preg_replace("/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/","$2",$post);

add newlines or line breaks after p closing tag with php

I have this text in a MySql database:
First paragraph very long.
Second paragraph very long.
Third paragraph.
I add p tags and it works:
$text = preg_replace("/\n/","<p>",$text);
$text = '<p>'.$text;
I try to add line breaks when I echo to a html page. I tried 3 different things. But none of them seem to work:
$text = preg_replace("/<\/p>/","</p>\n\n",$text);
$text = preg_replace("/<\/p>/","</p><br><br>",$text);
$text = nl2br($text);
echo $text;
If I go to the web inspector in the Safari browser, I get this:
<p>First paragraph very long.</p><p>Second paragraph very long.</p><p>Third paragraph.</p>
I would like to have this:
<p>First paragraph very long.</p>\n>\n
<p>Second paragraph very long.</p>\n>\n
<p>Third paragraph.</p>\n>\n
It seems that my regex does not select <\/p> even when I escape it. I do not understand. What is wrong?
Presuming you need newline control chars (and not html line break tags):
$text = "First paragraph very long.\nSecond paragraph very long.\nThird paragraph.";
$text = '<p>' . preg_replace("~\n~", "<p>\n\n</p>", trim($text)) . '</p>;
Note trim is used incase you have leading or trailing newlines, ~ is used as a delimiter, because / is a poor choice when dealing with html, causeing you to escape all over the place.
It is not apparent in the above example, but using some of your reqex as an example:
preg_replace("~</p>~","</p>\n\n",$text);
is much easier to read than:
preg_replace("/<\/p>/","</p>\n\n",$text);
Also, you dont need regex, you could just use str_replace:
$text = '<p>' .str_replace("\n", "<p>\n\n</p>", trim($text)) . '</p>;
Or even explode/implode:
$text = '<p>' . implode("</p>\n\n<p>", explode("\n", trim($text))) . '</p>';
If it was html line breaks you wanted, then you could just edit the replacement argument to:
"</p><br><br><p>"
in any of the above, but it would probably be better to use some css:
p{
margin-bottom:10px;
}
You don't need regex, simple str_replace works (in your example):
$text = str_replace( "</p><p>","</p>\n<p>",$text );

For every line beginning with 4 spaces, add text-indent tags

I've got text where some lines are indented with 4 spaces. I've been trying to write a regex which would find every line beginning with 4 spaces and put a <span class="indented"> at the beginning and a </span> at the end. I'm no good at regex yet, though, so it came to nothing. Is there a way to do it?
(I'm working in PHP, in case there's an option easier than regex).
Example:
Text text text
Indented text text text
More text text text
A bit more text text.
to:
Text text text
<span class="indented">Indented text text text</span>
More text text text
A bit more text text.
The following will match lines starting with at least 4 spaces or a tab character:
$str = preg_replace("/^(?: {4,}|\t *)(.*)$/m", "<span class=\"indented\">$1</span>", $str);
I had to do something similar, and one thing I might suggest is changing the goal formatting to be
<span class="tab"></span>Indented text text text
You can then set your css something like .tab {width:4em;} and instead of using preg_replace and regexes, you can do
str_replace($str, " ", "<span class='tab'></span>");
This has the benefit of allowing for 8 spaces to turn into a double width tab easily.
I think this should work:
//get each line as an item in an array
$array_of_lines = explode("\n", $your_string_of_lines);
foreach($array_of_lines as $line) {
// First four characters
$first_four = substr($line, 0, 4);
if($first_four == ' ') {
$line = trim($line);
$line = '<span class="indented">'.$line.'</span>';
}
$output[] = $line;
}
echo implode("\n",$output);

preg_replace question

I'm trying to use preg_replace to strip out a section of code but I am having problems getting it to work right.
Code Example:
$str = '<p class="code">some string here</p>';
PHP I'm using:
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
preg_replace($pattern,"", $str);
This strips out the code just as I want with the exception of the space between the p and class.
Returns:
some string here //notice the single space at the beginning.
I'm trying to get:
some string here //no space at the beginning.
I have been beating my head against the wall trying to find a solution. The reason I'm trying to strip it out in a chunk instead of breaking the preg_replace into pieces is because I don't want to change anything that may be in the string between the tags. Any ideas?
That does not happen for me (and it shouldn't).
It may be a space output somewhere else (use var_dump() to view the string).
You might want to look into this thread to see if you want to switch to using DOMDocument. It'll save you a great deal of headaches trying to parse through HTML.
Robust and Mature HTML Parser for PHP
test:
<?php
$str = '<p class="code">some string here</p>';
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
$result = preg_replace($pattern,"", $str);
var_dump($result);
result:
php pregrep.php
string(16) "some string here"
seems to work just fine.
Alex I figured out where I was picking up the extra space.
I was putting that code into a text area like this:
$str = '<p class="code">some string here</p>';
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
$strip_str = preg_replace($pattern,"", $str);
<textarea id="code_area" class="syntaxhl" name="code" cols="66" rows="5">
<?php echo $strip_str; ?>
</textarea>
This gave me my extra space but when I changed the code to:
<textarea id="code_area" class="syntaxhl" name="code" cols="66" rows="5"><?php echo $strip_str; ?></textarea>
No line spaces or breaks the extra space went away.
Why not use trim()?
$text = trim($text);
This removes white spaces around strings.

Stripping html tags using php

How can i strip html tag except the content inside the pre tag
code
$content="
<div id="wrapper">
Notes
</div>
<pre>
<div id="loginfos">asdasd</div>
</pre>
";
While using strip_tags($content,'') the html inside the pre tag too stripped of. but i don't want the html inside pre stripped off
Try :
echo strip_tags($text, '<pre>');
You may do the following:
Use preg_replace with 'e' modifier to replace contents of pre tags with some strings like ###1###, ###2###, etc. while storing this contents in some array
Run strip_tags()
Run preg_relace with 'e' modifier again to restore ###1###, etc. into original contents.
A bit kludgy but should work.
<?php
$document=html_entity_decode($content);
$search = array ("'<script[^>]*?>.*?</script>'si","'<[/!]*?[^<>]*?>'si","'([rn])[s]+'","'&(quot|#34);'i","'&(amp|#38);'i","'&(lt|#60);'i","'&(gt|#62);'i","'&(nbsp|#160);'i","'&(iexcl|#161);'i","'&(cent|#162);'i","'&(pound|#163);'i","'&(copy|#169);'i","'&#(d+);'e");
$replace = array ("","","\1","\"","&","<",">"," ",chr(161),chr(162),chr(163),chr(169),"chr(\1)");
$text = preg_replace($search, $replace, $document);
echo $text;
?>
$text = 'YOUR CODE HERE';
$org_text = $text;
// hide content within pre tags
$text = preg_replace( '/(<pre[^>]*>)(.*?)(<\/pre>)/is', '$1###pre###$3', $text );
// filter content
$text = strip_tags( $text, '<pre>' );
// insert back content of pre tags
if ( preg_match_all( '/(<pre[^>]*>)(.*?)(<\/pre>)/is', $org_text, $parts ) ) {
foreach ( $parts[2] as $code ) {
$text = preg_replace( '/###pre###/', $code, $text, 1 );
}
}
print_r( $text );
Ok!, you leave nothing but one choice: Regular Expressions... Nobody likes 'em, but they sure get the job done. First, replace the problematic text with something weird, like this:
preg_replace("#<pre>(.+?)</pre>#", "||k||", $content);
This will effectively change your
<pre> blah, blah, bllah....</pre>
for something else, and then call
strip_tags($content);
After that, you can just replace the original value in ||k||(or whatever you choose) and you'll get the desired result.
I think your content is not stored very well in the $content variable
could you check once by converting inner double quotes to single quotes
$content="
<div id='wrapper'>
Notes
</div>
<pre>
<div id='loginfos'>asdasd</div>
</pre>
";
strip_tags($content, '<pre>');
You may do the following:
Use preg_replace with 'e' modifier to replace contents of pre tags with some strings like ###1###, ###2###, etc. while storing this contents in some array
Run strip_tags()
Run preg_relace with 'e' modifier again to restore ###1###, etc. into original contents.
A bit kludgy but should work.
Could you please write full code. I understood, but something goes wrong. Please write full programming code

Categories