HOw to make this php class work as expected - php

Can anyone see what i have done incorreclty using this class it should change the word before to after but it just sits there doing nothing.
The second php pgm is the actual classs I am using..
<?php
include("parse.inc.php");
$bob = new parseClass();
$tag = "{Before}";
$replacement = "After";
$content = "My animal runs around all over the place and his name is {Before}.";
$bob->ReplaceTag($tag, $replacement, $content);
echo $bob;
?>
parse.inc.php (file name)
***************************
<?php
Class parseClass {
function ReplaceTag($tag, $replacement, $content) {
$content = str_replace($tag, $replacement, $content);
return $content;
}
}
// END Class parseClass
?>

In your case, you pass the content into class's function
Therefore, you should store the return value into variable first
$result = $bob->ReplaceTag($tag, $replacement, $content);
echo $result;

You just need to store the result of your function in a local variable, and print that.
$result = $bob->ReplaceTag($x, $y, $z);
print($result);

I guess you want to print the string having be replaced,so you should :
$result = $bob->ReplaceTag($tag, $replacement, $content);
echo $result;
Why are you use echo to print class?If you want to do this,please use "var_dump" or 'print_r' instead;

If the hard requirement is that you want to be able to echo the instance of parseClass, try this:
class parseClass
{
private $content;
public function ReplaceTag($tag, $replacement, $content)
{
$this->content = str_replace($tag, $replacement, $content);
}
public function __toString()
{
return $this->content;
}
}
$bob = new parseClass();
$tag = "{Before}";
$replacement = "After";
$content = "My animal runs around all over the place and his name is {Before}.";
$bob->ReplaceTag($tag, $replacement, $content);
echo $bob;
For reference, see:
http://php.net/manual/en/language.oop5.magic.php#object.tostring

Simply replace these two lines
$bob->ReplaceTag($tag, $replacement, $content);
echo $bob;
with
$content = $bob->ReplaceTag($tag, $replacement, $content);
echo $content;

Related

Str_replace with subject passed by reference

Given the following example:
public function replaceMyText($search, $replace, &$content)
{
$newContent = str_replace($search, $replace, $content, $count = 1)
$content = $newContent;
}
Can this cause a Warning that only variables can be passed by reference? If so, I can't fully understand why.
Should I assigned the $content to another variable before passing it to the str_replace function?
<?php
function replaceMyText($search, $replace, &$content)
{
$newContent = str_replace($search, $replace, $content, $count = 1);
$content = $newContent;
}
replaceMyText("123", "456", "123456");
using this function without variable will get a fatal error
Fatal error: Only variables can be passed by reference in /usercode/file.php on line 8
because
No other expressions should be passed by reference, as the result is undefined.
from http://php.net/manual/en/language.references.pass.php
you just can using by this
$a = "123456";
replaceMyText("123", "456", $a);
echo $a;
Sorry for my bad english. I hope it can help you.
EDIT
Please try this code :
function replaceMyText($search, $replace, $content)
{
$newContent = str_replace($search, $replace, $content,$count=1);
return $newContent;
}
$searchValue = "test";
$replaceWith = "magic trick";
$actualContent = "This is a test.";
$replaced = replaceMyText($searchValue,$replaceWith,$actualContent);
echo $replaced;

Replace variable with its value inside HTML without <?php ?>

Here is the situation. I have 2 files
content.php
<?php $my_var = "this is a variable"; ?>
<h1> php{my_var} </h1>
index.php
<?php include "content.php" ?>
The result should be:
<h1>this is a variable</h1>
I know how to work with preg_replace_callback. But I don't know how can I change php{my_var} with the value of $my_var.
All the logic should happens inside the index.php.
Edit
index.php
function replace_pattern($match)
{
what should I write here
}
echo preg_replace_callback("/php\:\{(.*)\}/", "replace_pattern", $Content);
Edit 2
Variables are not declare in the global scope
Note the added question-mark in the regular expression to make it less greedy.
$my_var = 'Hello World!';
// Get all defined variables
$vars = get_defined_vars();
$callback = function($match) use ($vars)
{
$varname = $match[1];
if (isset($vars[$varname])) {
return $vars[$varname]; // or htmlspecialchars($vars[$varname]);
} else {
return $varname . ' (doesn\'t exists)';
}
};
echo preg_replace_callback("/php\:\{(.*?)\}/", $callback, $Content);
Demo: http://phpfiddle.org/main/code/ax15-bpyw
Try this:
$my_var = "this is a variable";
$string = '<h1> php{my_var} </h1>';
$pattern = '/php{(.*)}/i';
preg_match($pattern, $string, $match);
$varName = $match[1];
$newString= preg_replace($pattern, $$varName, $string);
echo $newString;
But, warning!
In this case, i assume, if the code is php{somethin}, then there should be a $something variable. I used dynamic variable name. If you want to use only $my_var then use like this:
$newString= preg_replace($pattern, $my_var, $string);

Create and simplify links from body of text in PHP

I need to extract all links in a body of text in php and make them clickable. The problem is I can't seem to simplify the text of the link in any way.
I tried using preg_replace_callback but I can't seem to get the trimming function working properly:
function trimUrl($url){
$maxLength = 3;
if(strlen($url)>$maxLength){
$urlShort = substr($str,0,$maxLength).'...';
}
else{
$urlShort = $url;
}
return $urlShort;
}
function enableLinks($text){
return preg_replace_callback("!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9#:%_+.~#?&;//=]+)!i", "<a href='$1' target='_blank'>".trimUrl("$1")."</a>", $text);
}
enableLinks("Visit more work at http://www.google.com");
How can I run a second function within the preg_replace_callback that trims the output text?
What if you used a function inside that function. So if the first function evaluates to true then run this next function? And also try using preg_replace_callback in a variable format so its easier to work with
First, you are using substring(). Where have you defined the variable $str? And, if you do this:
$var = preg_replace_callback("!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9#:%_+.~#?&;//=]+)!i", "<a href='$1' target='_blank'>".trimUrl("$1")."</a>", $text);
Than can you use a new function:
return function($var);
Ended up using a more expanded function to achieve this, works on multiple urls with or without "http://":
function trimUrlOutput($url){
$maxLength = 30;
if(strlen($url)>$maxLength){
$urlShort = substr($url,0,$maxLength).'...';
}
else{
$urlShort = $url;
}
return $urlShort;
}
function enableLinks($text){
$text = ereg_replace( "www\.", "http://www.", $text );
$text = ereg_replace( "http://http://www\.", "http://www.", $text );
$text = ereg_replace( "https://http://www\.", "https://www.", $text );
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match_all($reg_exUrl, $text, $url)) {
$matches = array_unique($url[0]);
foreach($matches as $match) {
$linkText = trimUrlOutput($match);
$replacement = "<a href=".$match." target='_blank'>{$linkText}</a>";
$text = str_replace($match,$replacement,$text);
}
return $text;
}
else{
return $text;
}
}
enableLinks("Visit more work at http://www.google.com");
Hope this helps someone.

Remove the first paragraph tags from string

String
"<p>This is </p><p>Stackoverflow</p><p>site for programmers</p>"
Required Output
"This is <p>Stackoverflow</p><p>site for programmers</p>"
Small function
function remove_p($string)
{
$first_p=substr($string,0,3);
$p="<p>";
if($first_p==$p)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('</p>','',$string,$temp=1);
}
return $string;
}
But it removes all the <p> </p> tags.Why so?
I am basically writing this to remove the first paragraph tags created by ckeditor.
str_replace acts on all occurrences of a substring, not just the first. You will want to use a different function.
$string = preg_replace('~<p>(.*?)</p>~is', '$1', $string, /* limit */ 1);
To only remove the first <p> and </p> if at the start of the string, add a ^ after the first /.
See also: Using str_replace so that it only acts on the first match?
function replaceFirst($input, $search, $replacement){
$pos = stripos($input, $search);
if($pos === false){
return $input;
}
else{
$result = substr_replace($input, $replacement, $pos, strlen($search));
return $result;
}
}
$string = "This is <p>Stackoverflow</p><p>site for programmers</p>";
echo $string;
echo replaceFirst($string, '<p>', '');
Output:
This is <p>Stackoverflow</p><p>site for programmers</p>
This is Stackoverflow</p><p>site for programmers</p>
Source: #2031045
Hope this helps!
$str = "This is <p>Stackoverflow</p><p>site for programmers</p>";
function remove_p($string)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('<\p>','',$string,$temp=1);
return $string;
}
echo(remove_p($str));
The result is:
This is Stackoverflow
site for programmers
Try using the method of this answer.
function remove_p($string)
{
return replaceFirst(replaceFirst($string, '<p>', ''), '</p>', '');
}
Or read about Regular Expressions.

How to find a string in a variable using PHP and regular expressions

I am trying to find the word and add a number next to it. How could he do? I tried with the code below, but I could not. Could anyone help me?
Thank you!
$string = 'I220ABCD I220ABCDEF I220ABCDEFG'
if (preg_match("/I220.*/", $string, $matches)) {
echo $matches[0];
}
Expected result:
I220ABCD9
I220ABCDEF10
I220ABCDEFG11
Use preg_replace_callback instead like this:
$str = 'I220AB FRRRR CD I221ABCDEF I220AB DSFDSF CDEFG';
$repl= preg_replace_callback('~(I220[^\s]+)~', function($m) {
static $i=9;
return $m[1] . $i++;
}, $str);
echo $repl\n"; // I220AB9 FRRRR CD I221ABCDEF I220AB10 DSFDSF CDEFG
I dont know what your requirnments for adding the number at the end are so i just incremeneted during the loop;
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
$arrayStrings = explode(" ", $string);
$int = 9;
$newString = '';
foreach($arrayStrings as $stringItem)
{
if (preg_match("/I220.*/", $stringItem, $matches))
{
$stringItem = $stringItem.$int;
$newString = $newString.$stringItem." ";
$int++;
}
}
echo $newString;
Use preg_replace_callback():
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
// This requires PHP5.3+ since it's using an anonymous function
$result = preg_replace_callback('/I220[^\s]*/', function($match){
return($match[0].rand(0,10000)); // Add a random number between 0-10000
}, $string);
echo $result; // I220ABCD3863 I220ABCDEF5640 I220ABCDEFG989
Online demo.
You'll need to use a catch block in your regex e.g. "/I220([^ ]+)/" and if you want them all, you'll need to use preg_match_all, too.
preg_replace_callback with your needs:
$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
class MyClass{
private static $i = 9;
private static function callback($matches){
return $matches[0] . self::$i++;
}
public static function replaceString($string){
return preg_replace_callback('/I220[^\s]+/',"self::callback",$string);
}
}
echo(MyClass::replaceString($string));
of course you can edit to class to initialize the way you want

Categories