I'm using str_replace() PHP function which doesn't replace empty string.
Is it possible to replace it using some other PHP functions?
Here is my code:
$var = "text1|text2";
$expn = explode("|", $var);
$new = "new text";
str_replace($expn[1], $new, $var);
This code really works, but if the second value is empty it doesn't:
$var = "text1|";
$expn = explode("|", $var);
$new = "new text";
str_replace($expn[1], $new, $var);
I want this to echo text1|new text but it doesnt. In the first case it does without a problem. I want this to be changed anyway, it doesn't depend if it's empty or not.
Thanks in advance.
Try this after your explode():
if ($expn[1] == '') {
$var .= 'new text';
} else {
str_replace($expn[1], $new, $var);
}
Related
I would like to make a [code][/code] tag for bbcode so that what would be inside wouldn't be taken into account by the php regex that I made.
Example :
Hello [b]newbie[/b], to write in bold, use the following : [code][b](YOURTEXT)[/b][/code]
Should return in HTML :
Hello <strong>newbie</strong>, to write in bold, use the following : [b](YOURTEXT)[/b]
Here is a view of a part of my bbcode function :
<?
function bbcode($var) {
$var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var);
$var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
$var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);
return $var;
}
?>
Thank you in advance for your kind help !
EDIT :
Here is how I finally made it work :
<?
function bbcode($var) {
$var2 = preg_split('`(\[code].*?\[/code])`isU', $var, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var);
$var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
$var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);
$var = preg_replace('`(\[code].*?\[/code])`isU', $var2[1], $var);
$var = preg_replace('`\[code\](.+)\[/code\]`isU', '<div>$1</div>', $var);
return $var;
}
$text = 'Hello [b]newbie[/b], to write in bold, use the following [u]lol[/u] : [code][b](YOURTEXT) [u]lol[/u][/b][/code] [b][u]LOL[/u][/b]';
echo bbcode($text);
?>
HOWEVER, there is a new problem left : if the character chain starts directly with '[code]' for example
[code][b]hello[/b][/code] test
than the result will be :
test test
This is because $var2[1] now leads to what comes after the [/code].
Could someone please help me to make a better delimitation that would also work for that second character chain ? Thank you in advance !
Finally, I solve all the problems I had with that :
<?
function bbcode($var) {
$var2 = getStringBetween($var, '[code]', '[/code]');
$var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var);
$var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
$var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);
$var = preg_replace('`(\[code].+\[/code])`isU', '<div>'.$var2.'</div>', $var);
return $var;
}
function getStringBetween($str,$from,$to)
{
$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}
$text = 'Hello [b]newbie[/b], to write in bold, use the following [u]lol[/u] : [code][b](YOURTEXT) [u]lol[/u][/b][/code] [b][u]LOL[/u][/b]';
echo bbcode($text);
?>
I have a html doc that has links in it.
Example :
http://mysite1.com/test/whatIwant/Idontwantthis
http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither
I want to replace these with:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
How can I do this? I feel like the only way is to use str_ireplace to get the value that I want and append it to the other link, I just can't seem to remove the part after the value that I want.
I use:
$var= str_ireplace("http://mysite1.com/test/", "http://myothersite.com/", $var);
But then I get the after value still on the link:
http://myothersite.com/whatIwant/Idontwantthis
I tried and now am turning to the community for help.
Thanks
Oh and they are enclosed in the tag with class and other attributes, all I need to change is the URL as explained above.
The links are not in an array they are being edited from a javascript file so they will be in a large variable as text.
$examples =
'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither'
;
Edit: using your updated example, you can split those URLs up by the whitespace between them:
$examples = 'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant3/Idontwantthiseither';
$examples = explode(' ', $examples);
Alternative example array:
$examples = array(
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis',
'http://mysite1.com/test/whatIwant3/Idontwantthiseither'
);
Regex solution:
$pattern = '/^(?:http|https):\/\/.+\/.*\/(.+)\/.*$/Um';
$replace = 'http://myothersite.com/$1';
foreach($examples as $example) {
echo preg_replace($pattern, $replace, $example);
}
Non-regex solution:
foreach($examples as $example) {
// remove the original domain name
$first = str_ireplace('http://mysite1.com/test/', '', $example);
// prepend the new domain name with the first part of the remaining URL
// e.g. strip everything after the first slash
echo 'http://myothersite.com/' . explode('/', $first)[0];
}
Note: using explode(...)[0] is array dereferencing, and is supported in PHP >= 5.4.0. For previous versions of PHP, use a variable to store the array before referencing it:
$bits = explode('/', $first);
echo 'http://myothersite.com/' . $bits[0];
From the manual:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
Example output:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
This function should do the job.
<?php
function EditLink($link)
{
$link = explode("/",$link);
return $link[4];
}
$new_link = "http://myothersite.com/".EditLink("http://mysite1.com/test/whatIwant/Idontwantthis")."";
echo $new_link;
?>
Try this no regex:
$urls = array(
'http://mysite1.com/test/whatIwant3/Idontwantthiseither',
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis'
);
$new_site = "http://myothersite.com/";
foreach ($urls as $url) {
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
echo $var . '<br>';
}
As of PHP 5.3:
$new_urls = array_map(function($url) { // anonymous function
global $new_site;
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
return $var;
}, $urls);
echo implode('<br>', $new_urls);
Sorry by my last answer, you was right, the order was correct.
Try this one with pre_replace, I beleave could solve the problem:
$var = "http://mysite1.com/test/whatIwant/Idontwantthis";
$var = preg_replace("/http\:\/\/mysite1.com\/([^\/]+)\/?.*/", "http://myothersite.com/$1", $var);
echo $var;
php noob here trying to create a function but can't quite find the resource on the web that rids my confusions. Here it goes;
I want to create a function which takes a variable name, for example
Thief's Wit (4)
And converts it to
thiefswit.jpg
So far, here is what I have
THIS CODE IS LOADED TO TEST MY FUNCTION
require_once 'functions.php';
$mod = "Thief's Wit (4)";
convertImage($mod);
echo $mod;
?>
THIS CODE IS THE ACTUAL FUNCTION
function convertImage($string)
{
$string = preg_replace('/\s+/', '', $string);
$string = str_replace("'", "", $string);
$stringlength = strlen($string);
substr ($string, 0, ($stringlength-4));
$string = strtolower ($string);
$string = "$string" . ".jpg";
return $string;
}
?>
The format of the strings will always be
NAME HERE (4)
which is why I substr the length-4.
When I run this function, it echoes the original string.
Any help here?
I'm new to PHP and don't really understand
a) What the 'return' does at the end of the function and
b) Does the function inherently know to replace "$string" with the variable you tell it to act on in another file? In this case $mod.
Thanks!
You need to save the output of the function:
$mod = "Thief's Wit (4)";
$mod = convertImage($mod); // save the return value to $mod variable
echo $mod;
The return value of a function is the value you get from calling a function. So convertImage($mod) will have the value that you return. At this point, you need to store the results to a variable, which you can do by doing $mod = convertImage($mod);
An alternative would be to "pass by reference", where modifying the arguments of your function will modify the variables themselves.
function convertImage(&$string) // use &$string to pass by reference
{
$string = preg_replace('/\s+/', '', $string);
$string = str_replace("'", "", $string);
$stringlength = strlen($string);
substr ($string, 0, ($stringlength-4));
$string = strtolower ($string);
$string = "$string" . ".jpg";
//return $string; this won't be needed anymore
}
...
$mod = "Thief's Wit (4)";
convertImage($mod);
echo $mod;
You have to either return the new string you created
$mod = convertImage($mod);
Or pass by reference, which means that the function convertImage is working with the same reference to the passed in string as its caller
function convertImage(&$string) {...}
convertImage($mod); // $mod will point to a new string after the call
function convertImage(&$string) {
$string = strtolower(preg_replace("/[^a-zA-Z]+/", "", $string));
}
should do all you need - it will strip any punctuation and numbers etc, and make it lower case.
edited to allow passing by reference
You aren't assigning the variable value anywhere. To get the actual result, you'd have the function return value to a variable, like so:
$mod = convertImage($mod);
Once the actual function output is stored in a variable, you'll be able to use it anywhere as you like.
Demo: http://codepad.org/naFB74K6
<?php
function convertImage(&$string)
{
$string = preg_replace('/\s+/', '', $string); //Thief'sWit(4)
$string = str_replace("'", "", $string); //ThiefsWit(4)
$string = substr($string, 0, strlen($string)-3); //ThiefsWit
$string = strtolower($string); //thiefswit
return $string.".jpg";
}
$mod = "Thief's Wit (4)";
convertImage($mod);
echo $mod;
?>
I have this string
$s = 'Yo be [diggin = array("fruit"=> "apple")] scriptzors!';
which then gets checked by
$matches = null;
preg_match_all('/\[(.*?)\]/', $s, $matches);
var_dump($matches[1]);
but what I want it to do is the following, it should return the following
print "yo be";
$this->diggin(SEND ARRAY HERE);
print "scriptzors!";
EDIT to show issue with below answer
$s = 'Yo be [diggin = array("fruit"=>"apple")] scriptzors!';
$matches = null;
preg_match_all('/\[(.*?)\]/', $s, $matches);
$var = explode(' = ', $matches[1]);
print $var[0]; //THIS DOES NOT PRINT
You're sort of close. You can explode the string with = but with spaces included around the =. Then the first element would be the function name, in this case diggin and the second element would be the array but as a string. You'll need to eval that one so that it'll be a proper array data type.
$var = explode(' = ', $matches[1][0]);
call_user_func_array(array($this, $var[0]), eval($var[1] . ';'));
// or do
$this->{var[0]}(eval($val[1] . ';'));
As an alternative, you can also modify the regex so that you don't have to call explode.
preg_match_all('/\[([a-z0-9_]*)\s*?=\s*(.*)\]/i', $s, $matches);
Either way, you'll want to make sure that you sanitize the user input because eval can be evil.
This will call the function without using eval and exposing yourself to code injection.
preg_match_all('/\[([a-z0-9_]*)\s*?=\s*array\((.*)*\)\]/i', $s, $matches);
$var = explode(',', $matches[2][0]);
$result = array();
foreach ($var as $value) {
$keyvaluepair = explode('=>', $value);
$result[$keyvaluepair[0]] = $keyvaluepair[1];
}
$this->{var[0]}($result);
I am trying to trim a string in PHP so that I can only get certain text from the String.
I have an email stored to a String for instance some_name#somedomain.com .
How can I remove the text after the '#' so that I would only 'some_name'?
In PHP you can do :
$string = 'some_name#somedomain.com';
$res = explode('#', $string);
echo $res[0];
Or you can use regexp, string functions in php ... etc
You should know both ways to do this:
substr
$mail = "some_name#somedomain.com";
echo substr($mail, 0, strpos($mail, '#') );
explode
list($name, $domain) = explode('#', $mail);
echo $name;
If you don't need the $domain you can skip it:
list($name) = explode('#', $mail);
More about list.
Demo: http://ideone.com/lbvQF
$str = 'some_name#somedomain.com';
$strpos = strpos($str, "#");
echo $email = substr($str, 0,$strpos);
you can try this to get string before #
Try This
$str1 = "Hello World";
echo trim($str1,"World");
You could try split using regex and the # symbol. This will return two Strings which you can then use just to acquire the 'some_name'.
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
String s = "some_name#somedomain.com";
String name = s.substring(0,s.indexOf("#");