Everything between "[reply]" and extract the reply number - php

Please take a look at the following situation below.
[reply="292"] Text Here [/reply]
What I am trying to get is the number between the quotations in reply="NUMBERS". I want to extract that to one variable and the text between [reply="NUMBER"] this text here [/reply] to another variable.
So for this example:
[reply="292"] Text Here [/reply]
I want to extract the reply number: 292 and the text between the reply tags: Text here.
I have tried this:
\[reply\=\"]([A-Z]\w)\[\/reply]
But this only works until the reply tag, doesn't work after that. How can I go about doing this?

I left generic (. *), but you can specify a type like decimal (\d+).
php:
$s = '[reply="292"] Text Here [/reply]';
$expr = '/\[reply=\"(.*)\"\](.*)\[\/reply\]/';
if(preg_match($expr,$s,$r)){
var_dump($r);
}
javascript:
s = '[reply="292"] Text Here [/reply]'
s.match(/\[reply=\"(.*)\"\](.*)\[\/reply\]/)
//["[reply="292"] Text Here [/reply]", "292", " Text Here "]

Easy!
\[reply\=\"(\d+)\"](.*?)\[\/reply]
Explanation
\d for digit
+ for 1 or more occurrence of the specified character.
[\w\s] for any character in word and whitespace (\s)
Then apply it to PHP like this:
<?php
$str = "[reply=\"292\"] Text Here [/reply]";
preg_match('/\[reply\=\"(\d+)\"]([\w\s]+)\[\/reply]/', $str, $re);
print_r($re[1]); // printing group 1, the reply number
print_r($re[2]); // printing group 2, the text
?>
Important!!
Just get the group value, not all. You only need some of it anyway.

Related

How to use preg_replace with url encoded $_GET?

I have a an url which looks like this https://URL.DOMAIN/blog.php?id=43&q=echo%20%27test%27.
When I use <?php echo $_GET['q'] ?> it displays echo 'test' which is what I want.
I am using this variable inside a preg_replace function which is basically made to apply a yellow background under matched strings:
preg_replace('/\b('.$_GET['q'].')\b/iu', '<span class="research-news-found">$1</span>', $news_content);
It works perfectly for "normal" strings like "apple" or whatever, but when there is a ' inside the search query it doesn't match anything.
Code example
$news_content = $news_display['news_description'];
if(isset($_GET['q'])){
$news_content = preg_replace('/\b('.$_GET['q'].')\b/iu', '<span class="research-news-found">$1</span>', $news_content);
}
$news_display['news_description'] contains the text output from DB.
Just make the pattern greedy ? and remove the trailing word boundary \b since ' is not a word character and is a word boundary:
$news_content = preg_replace('/\b('.$_GET['q'].'?)/iu',
'<span class="research-news-found">$1</span>',
$news_content);
Demo
But if you are hoping that it will actually echo test, then no. You would need to restructure your question to state what you want to achieve, not how to get this replacement to work.

PHPWord/TemplateProcessor How to make paragraphs

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.

how to do echo from a string, only from values that are between a specific stretch[href tag] of the string?

[PHP]I have a variable for storing strings (a BIIGGG page source code as string), I want to echo only interesting strings (that I need to extract to use in a project, dozens of them), and they are inside the quotation marks of the tag
but I just want to capture the values that start with the letter: N (news)
[<a href="/news7044449/exclusive_news_sunday_"]
<a href="/n[ews7044449/exclusive_news_sunday_]"
that is, I think you will have to work with match using: [a href="/n]
how to do that to define that the echo will delete all the texts of the variable, showing only:
note that there are other hrefs tags with values that start with other letters, such as the letter 'P' : href="/profiles... (This does not interest me.)
$string = '</div><span class="news-hd-mark">HD</span></div><p>exclusive_news_sunday_</p><p class="metadata"><span class="bg">Czech AV<span class="mobile-hide"> - 5.4M Views</span>
- <span class="duration">7 min</span></span></p></div><script>xv.thumbs.preparenews(7044449);</script>
<div id="news_31720715" class="thumb-block "><div class="thumb-inside"><div class="thumb"><a href="/news31720715/my_sister_running_every_single_morning"><img src="https://static-hw.xnewss.com/img/lightbox/lightbox-blank.gif"';
I imagine something like this:
$removes_everything_except_values_from_the_href_tag_starting_with_the_letter_n = ('/something regex expresion I think /' or preg_match, substring?);
echo $string = str_replace($removes_everything_except_values_from_the_href_tag_starting_with_the_letter_n,'',$string);
expected output: /news7044449/exclusive_news_sunday_
NOTE: it is not essential to be through a variable, it can be from a .txt file the place where the extracts will be extracted, and not necessarily a variable.
thanks.
I believe this will help her.
<?php
$source = file_get_contents("code.html");
preg_match_all("/<a href=\"(\/n(?:.+?))\"[^>]*>/", $source, $results);
var_export( end($results) );
Step by Step Regex:
Regex Demo
Regex Debugger
To get just the links out of the $results array from Valdeir's answer:
foreach ($results as $r) {
echo $r;
// alt: to display them with an HTML break tag after each one
echo $r."<br>\n";
}

PHP replace : find and replace the same characters with different text

How can I find and replace the same characters in a string with two different characters? I.E. The first occurrence with one character, and the second one with another character, for the entire string in one go?
This is what I'm trying to do (so users need not type html in the body): I've used preg_replace here, but I'll willing to use anything else.
$str = $str = '>>Hello, this is code>> Here is some text >>This is more code>>';
$str = preg_replace('#[>>]+#','[code]',$str);
echo $str;
//output from the above
//[code]Hello, this is code[code] Here is some text [code]This is more code[code]
//expected output
//[code]Hello, this is code[/code] Here is some text [code]This is more code[/code]
But problem here is, both >> get replaced with [code]. Is it possible to somehow replace the first >> with [code] and the second >> with a [/code] for the entire output?
Does php have something to do this in one go? How can this be done?
$str = '>>Hello, this is code>> Here is some text >>This is more code>>';
echo preg_replace( "#>>([^>]+)>>#", "[code]$1[/code]", $str );
The above will fail if something like the following is your input:
>>Here is code >to break >stuff>>
To deal with this, use negative lookahead:
#>>((?!>[^>]).+?)>>#
will be your pattern.
echo preg_replace( "#>>((?!>[^>]).+?)>>#", "[code]$1[/code]", $str );

Add span or some tag to other language text in a phrase

In a PHP variable a mixed language context is present. An example is below:
$variable="This is sample text I am storing in the variable. இதன் கூடவே மற்ற மொழி எழுத்துக்களும் உள்ளன"
So the variable $variable contains both English and other language (Tamil in the above example).
Now I need to add a tag with class something enclosing the Tamil text such as:
$variable="This is sample text I am storing in the variable. <span class='tamil'>இதன் கூடவே மற்ற மொழி எழுத்துக்களும் உள்ளன</span>"
How to omit the English letters and punctuation symbols and add <span> to other language sentence completely or paragraph?
There's a unicode range that you can use to create a regex, this will help you find tamil chars in your text: http://unicode.org/charts/PDF/U0B80.pdf
[\u0B80-\u0BFA-]*
I have put together a playground for this example so that you can improve it to do what you need to do.
http://regex101.com/r/wT8hP4
The following is not gold plated code, but hope it can get you started.
<?php
$variable="This is sample text I am storing in the variable. இதன் கூடவே மற்ற மொழி எழுத்துக்களும் உள்ளன";
echo add_tamil_class($variable);
/**
* Adds a HTML Span tag around tamil text using regex
*/
function add_tamil_class($text) {
preg_match_all("/[\x{0B80}-\x{0BFA}]+/u", $text, $matches);
$tamilSentence = implode(' ', $matches[0]);
return str_replace(
$tamilSentence,
"<span class='tamil'>".$tamilSentence."</span>",
$text
);
}
As Filype mentioned, we can use the unicode ranges for this.
This should match even in cases like 'English' -> 'Tamil' -> 'English' -> 'Tamil'. Though it'll wrap extra spaces into the span.
/**
* #param String $str Input UTF-8 encoded string.
*/
function encapsulate_tamil($str)
{
return preg_replace('/[\x{0B80}-\x{0BFF}][\x{0B80}-\x{0BFF}\s]*/u',
'<span class=\'tamil\'>$0</span>', $str);
}

Categories