Bold First Line of Output - php

I need to add <b> tags around the first line of text, but not contained in a paragraph tag - rather just all the text before the first <br>.
It's a PHP string being echoed, so it seems to me pretty simple but I'm not sure how I'd get just that section of text, bold it, and then continue with the rest as normal.
$str = "First Line<br>SecondLine<br>Third Line<br>";
echo $str;
//output:
<b>First Line</b><br>SecondLine<br>ThirdLine<br>";

substr and strpos to the rescue!
$firstBreak = strpos($str, '<br>');
if($firstBreak === false) {
$str = "<b>$str</b>";
} else {
$str = '<b>' . substr($str, 0, $firstBreak) . '</b>' . substr($str, $firstBreak);
}

Try:
$first_line = explode('<br>', $str)[0];
$new_str = str_replace($first_line,'<b>'.$first_line.'</b>',$str);

Related

Check if a word occur in string and not to be in first and last

I am trying to check if word is occur in a string but not to be the first and last word, if its true then remove the space after and before of the word and replace with a underscore.
Input:
$str = 'This is a cool area";
Output:
$str = 'This is a_cool_area";
I want to check that the word 'cool' is inside the string but not a first and last word. if yes the remove the space & replace with '_'
You can use preg_replace to do this job, using this regex:
/(?<=\w)\s+(' . $word . ')\s+(?=\w)/i
which looks for the word, surrounded by at least one word character on either side (to prevent matching at the beginning or ending of the sentence). Usage in PHP:
$str = 'This is a cool area';
$word = 'cool';
$str = preg_replace('/(?<=\w)\s+(' . $word . ')\s+(?=\w)/i', '_$1_', $str);
echo $str . "\n";
$str = ' Cool areas are cool ';
$str = preg_replace('/(?<=\w)\s+(' . $word . ')\s+(?=\w)/i', '_$1_', $str);
echo $str . "\n";
Output:
This is a_cool_area
Cool areas are cool
Demo on 3v4l.org
function checkWord($str, $word)
{
$arr = explode(" ", $str);
$newArr = array_slice($arr, 1, -1);
$key = array_search($word, $newArr);
if($key !== false)
{
return implode('_',array_slice($arr, $key, 3));
}
else
{
return $str;
}
}
echo checkWord('This is a cool area', 'cool');

How to remove "<>" brackets from string in php?

$cont=htmlspecialchars(file_get_contents("https://myanimelist.net/anime/30276/One_Punch_Man"));
function getBetween($string, $start = "", $end = ""){
if (strpos($string, $start)) { // required if $start not exist in $string
$startCharCount = strpos($string, $start) + strlen($start);
$firstSubStr = substr($string, $startCharCount, strlen($string));
$endCharCount = strpos($firstSubStr, $end);
if ($endCharCount == 0) {
$endCharCount = strlen($firstSubStr);
}
return substr($firstSubStr, 0, $endCharCount);
} else {
return '';
}
}
$name=getBetween($cont,'title',' - MyAnimeList.net');
//$name=preg_replace('/[^a-zA-Z0-9 \p{L}]/m', '', $name);
preg_replace('/(*UTF8)[\>\<]/m', '', $name);
trim($name," ");
//$name=str_replace("gt", "", $name);
echo $name;
i want to find the text between title tags. how to do this?
for example in this page title contains 'One Punch Man - MyAnimeList.net' i want to get that
Just use string replace function:
$string = '<BoomBox>';
$string = str_replace('<', '', $string);
$string = str_replace('>', '', $string);
echo $string; // output: Boombox
http://php.net/manual/en/function.str-replace.php
You edited your answer, and we can now see you are dealing with XML/HTML. It's always better to work with the DOM classes. Never use regex! There is a famous Stack Overflow post explaining why never to parse html with regex. Try this solution instead:
<?php
$dom = new DOMDocument();
$dom->loadHTML('<title>BoomBox</title>');
echo $dom->getElementsByTagName('title')->item(0)->textContent;
http://php.net/manual/en/class.domdocument.php
http://php.net/manual/en/class.domnode.php
See it working here https://3v4l.org/EjPQd
You can use preg_replace();, or strip_tags();.
Example preg_replace();:
$str = '> One Punch Man';
$new = preg_replace('/[^a-zA-Z0-9 \p{L}]/m', '', $str);
echo $new;
Output: One Punch Man
Above example will only allow a-z, A-Z and 0-9. You can expand this.
Example strip_tags();:
$str = '<title> BoomBox </title>';
$another = strip_tags($str);
echo $another;
Output: BoomBox
Documentation:
http://php.net/manual/en/function.preg-replace.php // preg_replace();
http://php.net/manual/en/function.strip-tags.php // strip_tags();
You can also use a single call to str_replace with the ['<','>'] as the search argument:
$string = '<BoomBox>';
echo str_replace(['<', '>'], '', $string) . PHP_EOL;
// => Boombox
Or, you may use a regex with preg_replace (especially, if you plan on adding more restrictions for in-context matching to it):
echo preg_replace('~[<>]~', '', $string);
// => Boombox
See the PHP demo.

How to remove anything character after the part of link from string?

I have make a try like this:
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-13);
and the output work :
localhost/product/-/123456 cause this just for above link with 13 character after /-/123456
How to remove all? i try
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-(.*));
not work and error sintax.
and i try
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-999);
the output is empty..
Assume there are no number after localhost/product/-/123456, then I will just trim it with below
$string = "localhost/product/-/123456-Ebook-Guitar";
echo rtrim($string, "a..zA..Z-"); // localhost/product/-/123456
Another non-regex version, but require 5.3.0+
$str = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo dirname($str) . "/" . strstr(basename($str), "-", true); //localhost/product/-/123456
Heres a more flexibility way but involve in regex
$string = "localhost/product/-/123456-Ebook-Guitar";
echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456
$string = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456
This should match capture everything up to the number and remove everything afterward
regex101: localhost/product/-/123456-Ebook-Guitar
regex101: localhost/product/-/123456-Ebook-Guitar-1-pdf/
Not a one-liner, but this will do the trick:
$string = "localhost/product/-/123456-Ebook-Guitar";
// explode by "/"
$array1 = explode('/', $string);
// take the last element
$last = array_pop($array1);
// explode by "-"
$array2 = explode('-', $last);
// and finally, concatenate only what we want
$result = implode('/', $array1) . '/' . $array2[0];
// $result ---> "localhost/product/-/123456"

Preg Replace in PHP for Heading Tags

I have a markdown text content which I have to replace without using library functions.So I used preg replace for this.It works fine for some cases.For cases like heading
for eg Heading
=======
should be converted to <h1>Heading</h1> and also
##Sub heading should be converted to <h2>Sub heading</h2>
###Sub heading should be converted to <h3>Sub heading</h3>
I have tried
$text = preg_replace('/##(.+?)\n/s', '<h2>$1</h2>', $text);
The above code works but I need to have count of hash symbol and based on that I have to assign heading tags.
Anyone help me please....
Try using preg_replace_callback.
Something like this -
$regex = '/(#+)(.+?)\n/s';
$line = "##Sub heading\n ###sub-sub heading\n";
$line = preg_replace_callback(
$regex,
function($matches){
$h_num = strlen($matches[1]);
return "<h$h_num>".$matches[2]."</h$h_num>";
},
$line
);
echo $line;
The output would be something like this -
<h2>Sub heading</h2> <h3>sub-sub heading</h3>
EDIT
For the combined problem of using = for headings and # for sub-headings, the regex gets a bit more complicated, but the principle remains the same using preg_replace_callback.
Try this -
$regex = '/(?:(#+)(.+?)\n)|(?:(.+?)\n\s*=+\s*\n)/';
$line = "Heading\n=======\n##Sub heading\n ###sub-sub heading\n";
$line = preg_replace_callback(
$regex,
function($matches){
//var_dump($matches);
if($matches[1] == ""){
return "<h1>".$matches[3]."</h1>";
}else{
$h_num = strlen($matches[1]);
return "<h$h_num>".$matches[2]."</h$h_num>";
}
},
$line
);
echo $line;
Whose Output is -
<h1>Heading</h1><h2>Sub heading</h2> <h3>sub-sub heading</h3>
Do a preg_match_all like this:
$string = "#####asdsadsad";
preg_match_all("/^#/", $string, $matches);
var_dump ($matches);
And based on count of matches you can do whatever you want.
Or, use the preg_replace_callback function.
$input = "#This is my text";
$pattern = '/^(#+)(.+)/';
$mytext = preg_replace_callback($pattern, 'parseHashes', $input);
var_dump($mytext);
function parseHashes($input) {
var_dump($input);
$matches = array();
preg_match_all('/(#)/', $input[1], $matches);
var_dump($matches[0]);
var_dump(count($matches[0]));
$cnt = count($matches[0]);
if ($cnt <= 6 && $cnt > 0) {
return '<h' . $cnt . ' class="if you want class here">' . $input[2] . '</h' . $cnt . '>';
} else {
//This is not a valid h tag. Do whatever you want.
return false;
}
}

How to wrap string in span before and after all newlines in PHP?

Upon searching I found PHP function that do inserts before all newlines in a string which is
nl2br();
example:
<?php
echo nl2br("This is an example\r\n where line breaks\r\n added", false);
?>
Above code Output :
This is an example<br\>
where line breaks<br\>
added
What I wanted to have output instead of <br/> I will wrap the string with the tags before and after all newlines
example output from code above wrap string with span
<span>This is an example</span>
<span>where line breaks</span>
<span>added</span>
Is there PHP function exist to this? or a custom PHP function
$str = "This is an example\r\n where line breaks\r\n added";
$str = explode("\r\n",$str);
foreach($str as $key => $value) {
echo "<span>".$value."</span>";
}
You could do an "explode" on "\r\n" and loop over each value with a concatenated span.
Something like
$values = explode("\r\n", "one\r\ntwo\r\nthree\r\nfour")
$newvalues = ""
foreach($values as $value){
$newvalues = $newvalues . "<span>" . $value . "</span>"
}
Use file(). It will return the entire file as an array, each being a new line. Iterate through there and add your span's. Not the best way, but if you have a lot of files to do this for, it's just as easy as any other solution. Otherwise, just explode on your delimiter.
function splitToSpans($string) {
$lines = explode('\r\n', $string);
$finalString = '';
foreach ($lines as $line) {
$finalString .= '<span>' . $line . '</span>';
}
return $finalString;
}
Something like:
$strout = '';
$lines = explode(PHP_EOL, $input);
foreach ($lines as $line) {
$strout .= "<span>$line</span>";
}
Option 1:
<?php
$string = "Line 1
Line 2
Line 3";
$string = preg_replace('/^(.*)$/m', '<span>$1</span>', $string);
echo $string;
Option 2:
<?php
$string = "Line 1\r\nLine 2\r\nLine 3";
$string = array_map(function($value) {
return "<span>$value</span>";
}, explode("\r\n", $string));
echo implode("\r\n", $string);
This function splits the string based on either a CRLF or LF only and then wraps it into a <span> tag, applying proper escaping (important):
function nl2span($str)
{
$r = '';
foreach (preg_split("/\r?\n/", $str) as $line) {
$r .= '<span>' . htmlspecialchars($line). '</span>';
}
return $r;
}
If your line endings are always CRLF you can replace the preg_split() with a more conventional explode("\r\n", ...).
$string = "This is an example\r\n where line breaks\r\n added";
var_dump($string);
// string(46) "This is an example
// where line breaks
// added"
array_map(function($s){echo sprintf('<span>%s</span>', trim($s));}, explode("\r\n", $string));
// <span>This is an example</span>
// <span>where line breaks</span>
// <span>added</span>
This is useful:
function nl2span( $str) {
return '<span>' . implode( '</span><span>', explode( "\r\n", $str ) ) . '</span>';
}
Read through the answers, and noone had mentioned this solution...
$string = "This is an example\r\n where line breaks\r\n added";
echo '<span>' . str_replace('\r\n', '</span><span>', $string) . '</span>';

Categories