I have text in a with paragraphs, spaces and justied text like this coming from the database.
Hello.
My name is John.
Thank you
But when I use PHP Word with TemplateProcessor to move to a Word document it generates everything without paragraphs.
One solution I found for this was to do this:
$text=preg_replace('/\v+|\\\r\\\n/','<w:p/>',$TextWhitoutParagraphs);
He actually writes with paragraphs but only the first paragraph is justified.
How do I do this correctly with paragraphs and all text justified?
You can use cloneBlock. I used it with justified text and it worked perfectly. In your template use:
${paragraph}
${text}
${/paragraph}
And then explode your string by"\n":
$textData = explode("\n", $text);
$replacements = [];
foreach($textData as $text) {
$replacements[] = ['text' => $text];
}
$templateProcessor->cloneBlock('paragraph', count($replacements), true, false, $replacements);
The TemplateProcessor can only be used with single line strings (see docs: "Only single-line values can be replaced." http://phpword.readthedocs.io/en/latest/templates-processing.html)
What you could try is replacing your new lines with '' (closing the opened paragraph and starting a new one), but that would just be my guess right now. It always helps to check the resulting Word-XML for syntax-errors.
Related
I'm trying to convert text ($icon) to smiley image ($image). I used to do it with str_replace(), but that seems to perform the replace sequentially and as such it also replaces items in previously converted results (for example in the tag).
I am now using the following code:
foreach($smiliearray as $image => $icon){
$pattern[]="/(?<!\S)" . preg_quote($icon, '/') . "(?!\S)/u";
$replacement[]=" <img src='$image' border='0' alt=''> ";
}
$text = preg_replace($pattern,$replacement,$text);
This code works, but only if the smiley code is surrounded by whitespace. So basically if someone types ":);)", it won't catch it as two separate smilieys, but ":) ;)" does.
How can I fix it so that also a string of smileys (not separated by space) are converted?
Note that there can be unlimited kinds of smiley codes and smiley images. I do not know beforehand which ones, because other people can submit codes and smileys, so it is not just ":)" and ";)", but can also be "rofl", ":eh", ":-{", etc.
I can partially fix it by adding a \W non-word to the end of the 2nd capturegroup: (?!\S\W), and further by adding a 2nd $pattern and $replacement with a \W to the first capturegroup. But I don't think that is the way it should be done, and it only partially solves it.
I used to do it with str_replace(), but that seems to perform the
replace sequentially and as such it also replaces items in previously
converted results...
A good and true reason to use strtr(). You don't even need Regular Expressions:
<?php
// I assume your original array looks like this
$origSmileys = [
"/1.png" => ':)',
"/2.png" => ':(',
"/3.png" => ':P',
"/4.png" => '>:('
];
// sample input string
$str = " I'm :) but :(>:(:( now :P";
// iterating over smileys to add html tag
$newSmileys = array_map(function($value) {
return "<img src='$value' border='0' alt=''>";
}, array_flip($origSmileys));
// replace
echo strtr($str, $newSmileys);
Live demo
So i have a string and I used the strip_tags() function to remove all tags except IMG but I still have plain text next to my IMG element. Here a visual example
$myvariable = "This text needs to be removed<a href='blah_blah_blah'>Blah</a><img src='blah.jpg'>"
So using PHP strip_tags() I was able to remove all tags except the <img> tag (which is what I want). But the thing is now it didn't remove the text.
How do I remove the left over text? Text will always either before tag or after tag as well
[ADDED MORE DETAILS]
$description = 'crazy stuff<img src="https://scontent.cdninstagram.com/t51.2885-15/e15/14287934_1389514537744146_673363238_n.jpg?ig_cache_key=MTMzNzM3MzgwNjAyNDY5NDAzMA%3D%3D.2">';
that's what the variable is actually holding.
Thanks in Advance
Instead of replacing something you can very well extract the values you want:
(<(\w+).+</\2>)
To be used with preg_match(), see a demo on regex101.com.
IN PHP:
<?php
$regex = '~(<(\w+).+</\2>)~';
$string = 'crazy stuff<img src="https://scontent.cdninstagram.com/t51.2885-15/e15/14287934_1389514537744146_673363238_n.jpg?ig_cache_key=MTMzNzM3MzgwNjAyNDY5NDAzMA%3D%3D.2">here as well';
if (preg_match($regex, $string, $match)) {
echo $match[1];
}
?>
Please show your whole piece of code with the use of strip_tags.
You can try: preg_replace('~.*(<img[^>]+>)~', '$1', $myvariable);
I want to change Text1 to Text2.
Text1
Test1 is here<br>Now comes Test2<br>Then test 3<br><br>Thats it.
Text2
Test1 is here<br><br>Now comes Test2<br><br>Then test 3<br><br><br>Thats it.
i.e; add extra 'breakline' tag to the existing one in a string.
I tried it with preg_replace but can't figure it the way I wanted.
My Try -
preg_replace('/(?:(?:<br>)\s*)/s', "<br><br>", $posttext)
This should do it:
$text = preg_replace('/((<br>(\s+)?)+)/', '$1<br>', $text);
If you don't want to allow for newlines and spaces try: /((<br>)+)/
Try this:
preg_replace('/((?:<br>)+)\s*/s', "$1<br>", $posttext);
This captures a sequence of <br> tags, optionally followed by whitespace, and then adds one more after them.
DEMO
try this.
$text1 = "Test1 is here<br>Now comes Test2<br>Then test 3<br><br>Thats it.";
$text2 = substr($text1,0,strripos($text1,"<br>")) ."<br>" . substr($text1,strripos($text1,"<br>"));
My code works as follows:
Text comes to server (from textarea)
Text is ran through trim() then nl2br
But what is happening is it is adding a <br> but not removing the new line so
"
something"
becomes
"<br>
something"
which adds a double new line. Please help this error is ruining all formatting, I can give more code on request.
Creation of post:
Shortened creation method (Only showing relevent bits) Creation method:
BlogPost::Create(ParseStr($_POST['Content']));
ParseStr runs:
return nl2br(trim($Str));
Viewing of post:
echo "<span id='Content'>".BlogPosts::ParseBB(trim($StoredPost->Content))."</span>";
ParseBB runs:
$AllowedTags = array(
// i => Tag, Tag Replacement, Closing tag
0 => array("code","pre class='prettyprint'",true),
1 => array("center","span style='text-align:center;'",true),
2 => array("left","span style='text-align:right;'",true),
3 => array("right","span style='text-align:left;'",true)
);
$AllowedTagsStr = "<p><a><br><br/><b><i><u><img><h1><h2><h3><pre><hr><iframe><code><ul><li>";
$ParsedStr = $Str;
foreach($AllowedTags as $Tag)
{
$ParsedStr = str_replace("<".$Tag[0].">","<".$Tag[1].">",$ParsedStr);
if($Tag[2])
$ParsedStr = str_replace("</".$Tag[0].">","</".$Tag[1].">",$ParsedStr);
}
return strip_tags($ParsedStr,$AllowedTagsStr);
Example:
What I see:
What is shown:
It's because nl2br() doesn't remove new lines at all.
Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).
Use str_replace instead:
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
Aren't you using UTF-8 charset? If you are using multibyte character set (ie UTF-8), trim will not work well. You must use multibyte functions. Try something like this one: http://www.php.net/manual/en/ref.mbstring.php#102141
Inside <pre> you should not need to call nl2br function to display break lines.
Check if you really want to call nl2br when you are creating post. You probably need it only on displaying it.
What is the easiest way of applying highlighting of some text excluding text within OCCASIONAL tags "<...>"?
CLARIFICATION: I want the existing tags PRESERVED!
$t =
preg_replace(
"/(markdown)/",
"<strong>$1</strong>",
"This is essentially plain text apart from a few html tags generated with some
simplified markdown rules: <a href=markdown.html>[see here]</a>");
Which should display as:
"This is essentially plain text apart from a few html tags generated with some simplified markdown rules: see here"
... BUT NOT MESS UP the text inside the anchor tag (i.e. <a href=markdown.html> ).
I've heard the arguments of not parsing html with regular expressions, but here we're talking essentially about plain text except for minimal parsing of some markdown code.
Actually, this seems to work ok:
<?php
$item="markdown";
$t="This is essentially plain text apart from a few html tags generated
with some simplified markdown rules: <a href=markdown.html>[see here]</a>";
//_____1. apply emphasis_____
$t = preg_replace("|($item)|","<strong>$1</strong>",$t);
// "This is essentially plain text apart from a few html tags generated
// with some simplified <strong>markdown</strong> rules: <a href=
// <strong>markdown</strong>.html>[see here]</a>"
//_____2. remove emphasis if WITHIN opening and closing tag____
$t = preg_replace("|(<[^>]+?)(<strong>($item)</strong>)([^<]+?>)|","$1$3$4",$t);
// this preserves the text before ($1), after ($4)
// and inside <strong>..</strong> ($2), but without the tags ($3)
// "This is essentially plain text apart from a few html tags generated
// with some simplified <strong>markdown</strong> rules: <a href=markdown.html>
// [see here]</a>"
?>
A string like $item="odd|string" would cause some problems, but I won't be using that kind of string anyway... (probably needs htmlentities(...) or the like...)
You could split the string into tag/no-tag parts using preg_split:
$parts = preg_split('/(<(?:[^"\'>]|"[^"<]*"|\'[^\'<]*\')*>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
Then you can iterate the parts while skipping every even part (i.e. the tag parts) and apply your replacement on it:
for ($i=0, $n=count($parts); $i<$n; $i+=2) {
$parts[$i] = preg_replace("/(markdown)/", "<strong>$1</strong>", $parts[$i]);
}
At the end put everything back together with implode:
$str = implode('', $parts);
But note that this is really not the best solution. You should better use a proper HTML parser like PHP’s DOM library. See for example these related questions:
Highlight keywords in a paragraph
Regex / DOMDocument - match and replace text not in a link
First replace any string after a tag, but force your string is after a tag:
$t=preg_replace("|(>[^<]*)(markdown)|i",'$1<strong>$2</strong>',"<null>$t");
Then delete your forced tag:
$show=preg_replace("|<null>|",'',$show);
You could split your string into an array at every '<' or '>' using preg_split(), then loop through that array and replace only in entries not beginning with an '>'. Afterwards you combine your array to an string using implode().
This regex should strip all HTML opening and closing tags: /(<[.*?]>)+/
You can use it with preg_replace like this:
$test = "Hello <strong>World!</strong>";
$regex = "/(<.*?>)+/";
$result = preg_replace($regex,"",$test);
actually this is not very efficient, but it worked for me
$your_string = '...';
$search = 'markdown';
$left = '<strong>';
$right = '</strong>';
$left_Q = preg_quote($left, '#');
$right_Q = preg_quote($right, '#');
$search_Q = preg_quote($search, '#');
while(preg_match('#(>|^)[^<]*(?<!'.$left_Q.')'.$search_Q.'(?!'.$right_Q.')[^>]*(<|$)#isU', $your_string))
$your_string = preg_replace('#(^[^<]*|>[^<]*)(?<!'.$left_Q.')('.$search_Q.')(?!'.$right_Q.')([^>]*<|[^>]*$)#isU', '${1}'.$left.'${2}'.$right.'${3}', $your_string);
echo $your_string;