HTML output based in input number in PHP - php

I have values like so:
0.00000500
0.00003491
0.00086583
1.45304093
etc
I would like to run these through a PHP function so they become:
<span class="text-muted">0.00000</span>500
<span class="text-muted">0.0000</span>3491
<span class="text-muted">0.000</span>86583
1.45304093
What I have now is:
$input_number str_replace('0', '<span class="text-muted">0</span>', $input_number);
$input_number str_replace('.', '<span class="text-muted">.</span>', $input_number);
This is a bit 'aggressive' as it would replace every character instead of using the <span> once, but I guess that's OK, even if I have say 1000 numbers on a page. But the biggest problem I have is that my code would also 'mute' the last 2 digits in 0.00000500 which I don't want.

First of all:
$input_number = str_replace('0.', '', $input_number);
We are replacing 0. with empty string
Secondly:
Use preg replace()
$newNumber = preg_replace('/^0?/','<span class="text-muted">0</span>',$input_number);
Basically /^0?/ is looking for leading 0's which will replace with span, you can also replce with empty or anything you want.

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.

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";
}

Substr String With HTML In PHP

I have some text that comes back from my database like so:
<span rgb(61,="" 36,="" 36);="" font-family:="" 'frutiger="" neue="" w01="" book',="" 'helvetica="" neue',="" helvetica,="" arial,="" sans-serif;="" line-height:="" 23.8px;"="">The Department of ...
I use echo html_entity_decode($item->body); to display:
The Department of ...
However, if I use the PHP substr function on this content it never displays correctly. It will display the first x characters of HTML and not the HTML formatted text.
Here's what I tried: echo substr(html_entity_decode($item->body), 0, 5);
But it doesn't display anything. If I try an amount like 0, 200); it will display:
The Department of Molec
But this is most definitely not the first 200 characters of the formatted text because the first character is T.
My idea is that there must be way to format and then substr, even though I can't get it to work using html_entity_decode() and substr() by themselves.
Can anybody help me out here? Thanks!
Try to use this instead of html_entity_decode():
strip_tags($item->body);
strip_tags removes all HTML tags from the string. So you better of treating the string and then do something with it.
You will see the output in the source code, but it is not beeing rendered. The source code will show:
echo substr(html_entity_decode($item->body), 0, 5);
// Output: "<span"
What you probably want to do is search for the end of the html-tag, and display 5 characters after that, like:
$text = html_entity_decode($item->body);
$start = strpos( $text, '>' ) + 1;
echo substr( $text, $start, 5 );

preg_replace regex, split string to array

i have a string, where i need to split some values in to an array, what would be the best aproach?
String can look like this:
<span class="17">118</span><span style="display: inline">.</span><span style="display:none"></span>
or
125<span class="17">25</span>354
The rules are:
The string can start with a number, followed by a span or a div
The string can start with a span or a div
The string can end with a number
The string can end with a /span or a /div
The divs/spans can have a style/class
What i need, is to seperate the string, so that i get the elements seperated, such as:
0 => 123
1 => <span class="potato">123</span>
2 => <span style="color: black">123</span>
I have tried some costum regex, but regex is not my strong side:
$pattern = "/<div.(.*?)<\/div>|<span.(.*?)<\/span>/";
// i know it wont detect a number value prior to the div, thats also an issue, even if it worked
I cannot use simple_html_dom has to be done with REGEX.
Splitting the string between every >< might work, but ">(.*?)<" inserts after the < for some reason?
You might get better performance if you just load this string to DOM and then parse it manually programming your logic like:
var el = document.createElement( 'div' );
el.innerHTML = '125<span class="17">25</span>354';
// test your first element (125) index=0 (you can make for loop)
if(el.childNodes[0].nodeType == 3) alert('this is number first, validate it');
else if(el.childNodes[0].nodeType == 1) alert('this is span or div, test it');
// you can test for div or span with el.childNodes[0].nodeName
// store first element to your array
// then continue, test el.childNodes[next one, index=1 (span)...]
// then continue, test el.childNodes[next one, index=2 (354)...]
since you are already know are you looking for, this can be as simple as that
Try /(<(span|div)[^>]*>)*([^<]*)(<\/(span|div)>)*/
The Regex says something like 'there can be a span or div or nothing, then it has to be somthing then a /span or /div or nothing and that whole statement can match zero or many times.
Here is an example:
$pattern = "/(<(span|div)[^>]*>)*([^<]*)(<\/(span|div)>)*/";
$txt = '<span class="17">118</span><span style="display: inline">.</span><span style="display:none"></span>';
preg_match_all($pattern, $txt,$foo);
print_r($foo[0]);
$txt = '125<span class="17">25</span>354';
preg_match_all($pattern, $txt,$foo);
print_r($foo[0]);
?>

preg_replace between > and <

I have this:
<div> 16</div>
and I want this:
<div><span>16</span></div>
Currently, this is the only way I can make it work:
preg_replace("/(\D)(16)(\D)/", "$1<span>$2</span>$3", "<div> 16</div>")
If I leave off the $3, I get:
<div><span>16</span>/div>
Not quite sure what your after, but the following is more generic:
$value = "<div> 16 </div>";
echo(preg_replace('%(<(\D+)[^>]*>)\s*([^\s]*)\s*(</\2>)%', '\1<span>\3</span>\4', $value));
Which would result in:
<div><span>16</span></div>
Even if the value were:
<p> 16 </div>
It would result in:
<p><span>16</span></p>
I think you meant to say you're using the following:
print preg_replace("/(\\D+)(16)(\\D+)/", "$1<span>$2</span>$3", "<div>16</div>");
There's nothing wrong with that. $3 is going to contain everything matched in the second (\D+) group. If you leave it off, obviously it's not going to magically appear.
Note that your code in the question had some errors:
You need to escape your \'s in a string.
You need to use \D+ to match multiple characters.
You have a space before 16 in your string, but you're not taking this into account in your regex. I removed the space, but if you want to allow for it you should use \s* to match any number of whitespace characters.
The order of your parameters was incorrect.
Try following -
$str = "<div class=\"number\"> 16</div>";
$formatted_str = preg_replace("/(<div\b[^>]*>)(.*?)<\/div>/i", "$1<span>$2</span></div>", $s);
echo $formatted_str;
This is what ended up working the best:
preg_replace('/(<.*>)\s*('. $page . ')\s*(<.*>)/i', "$1" . '<span class="curPage">' . "$2" . '</span>' . "$3", $pagination)
What I found was that I didn't know for sure what tags would precede or follow the page number.

Categories