PHP replace hyphen with space [duplicate] - php

This question already has answers here:
how to replace hyphen with blank space / white space? php
(2 answers)
Closed 8 years ago.
So, I have a piece of code I am using in most of my pages which sets the page title as the file name. This is because I don't want to have to change the title each time I create a new page.
This all works fine, except I don't want to have spaces (or rather, %20) being shown in the url when the file name contains spaces. I'd much rather have hyphens in place of the spaces, as it looks cleaner to the user. However, this means PHP will set the page title also with hyphens instead of spaces, which, frankly, looks ugly.
Is there a way I can rewrite this code to replace the hyphens with spaces?
The code:
<?php
echo '<title>';
$path_parts = pathinfo(__FILE__);
echo ucfirst($path_parts['filename']);
echo " - Tom's basic Web Tutz";
echo '</title>';
?>

You can use str_replace to replace the - with a space.
<?php
echo '<title>';
$path_parts = pathinfo(__FILE__);
echo ucfirst(str_replace('-', ' ', $path_parts['filename']));
echo " - Tom's basic Web Tutz";
echo '</title>';
?>

You can use implode adn explode for this
$string = "the string";
$arr = explode("string to replace",$string);
$string = implode("string to add ",$arr);
echo $string;

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.

using fpdf : str_pad doesn't work with spaces, it works with other characters

I am adding a pad to my string, to fill with spaces, but it doesn't work
the code is here
<?php
$string1 = "Product 1 ";
$newString = str_pad($string1,100);
echo $newString."test";
echo "<br>";
$string2 = "Product 2222 ";
echo str_pad($string2,100," ")."test";
echo "<br>";
?>
the output is like this:
Product 1 test
Product 2222 test
You could try $str = str_pad($string2,(100*strlen(" "))," ")."test"; instead.
renders to a non-breaking-space in html (and when writing to document with fpdf).
Please note this can only work with fpdf when you tell it to write all lines as html! And the encoding should be utf-8 probably
$fpdf->Write(iconv('UTF-8', 'windows-1252', html_entity_decode($str)));
When the output of the PHP is converted to HTML, all the white spaces except the first are removed and it is the default feature of HTML and web browsers. so the output will not be correct.
You have to use the " " instead of white space in the str_pad function. HTML don't ignore the " " and against each existance of it, HTML adds a white space to the string.

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

Replace pattern between several string delimiters in PHP - Use of backreferences [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 6 years ago.
I have the following string in PHP:
$string = "<img src=\"url\" >HELLO WORLD<ol>I must replace the text after img and before ol.</ol>";
print htmlentities($string);
I want to find the substring HELLO WORLD (or whatever substring is, that is just an example of a text that will be completely dynamical), using the delimiters : "<img ... >" and "<ol>" and add <h3> delimiters. So the string above would result in:
<img src="url" ><h3>HELLO WORLD</h3><ol>I must replace the text after img and before ol.</ol>
I have tried the following code, of course with no success:
$string = preg_replace("/\<img (.*?)\> (.*?)\<ol\>/", "<img (.*?)><h3> (.*?)</h3></ol>", $string);
I know how to make very easy substituions, but the above condition is very far from my understanding.
I have found the answer by trial-and-error:
$string = "<img src=\"url\" >HELLO WORLD<ol>I must find the text after img and before ol.</ol>";
$string2 = preg_replace("/<img (.*?)>(.*?)<ol>/", "<img $1><h3>$2</h3><ol>", $string);
print htmlentities($string) . " <br />" . htmlentities($string2);
Explanation: I add the delimiters, and use $1 and $2 for matching the results between the delimiters in the right order.

regex - prevent two characters from being adjacent [duplicate]

This question already has answers here:
Batch script to replace PHP short open tags with <?php
(13 answers)
Closed 9 years ago.
I need to replace all PHP lines that are like <?=[something]?> with this: <?php echo [something]; ?> The problem is that there can be almost anything in that something clause even ? and < but they can't be adjacent. I am kinda new to regexes and wrote this very messy expression: \<\?\=([a-zA-Z0-9()=#<>\[\]\\/'"._$\?:, \-]*)([;]*)\?\> and replaced it with <?php echo \1; ?>.
It works but it can't match something like this:
<?=[something]?><tr><td><?=[something]?> when it's all in one line. It matches the whole line altogether.
Any help will be greatly appreciated.
This code should work:
$s = '<?=[something]?><tr><td><?=[something]?>';
$s = preg_replace('/(<\?)=\s*(\[[^]]*\])\s*(\?>)/', '$1php echo $2; $3', $s);
var_dump($s);
OUTPUT:
string(56) "<?php echo [something]; ?><tr><td><?php echo [something]; ?>"

Categories