php how to make a if str_replace? - php

$str is some value in a foreach.
$str = str_replace('_name_','_title_',$str);
how to make a if str_replace?
I want do the thing if have a str_replace then echo $str, else not, jump the current foreach then to the next. Thanks.

There is a fourth parameter to str_replace() that is set to the number of replacements performed. If nothing was replaced, it's set to 0. Drop a reference variable there, and then check it in your if statement:
foreach ($str_array as $str) {
$str = str_replace('_name_', '_title_', $str, $count);
if ($count > 0) {
echo $str;
}
}

If you need to test whether a string is found within another string, you can like this.
<?php
if(strpos('_name_', $str) === false) {
//String '_name_' is not found
//Do nothing, or you could change this to do something
} else {
//String '_name_' found
//Replacing it with string '_title_'
$str = str_replace('_name_','_title_',$str);
}
?>
http://php.net/manual/en/function.strpos.php
However you shouldn't need to, for this example. If you run str_replace on a string that has nothing to replace, it won't find anything to replace, and will just move on without making any replacements or changes.
Good luck.

I know this is an old question, but it gives me a guideline to solve my own checking problem, so my solution was:
$contn = "<p>String</p><p></p>";
$contn = str_replace("<p></p>","",$contn,$value);
if ($value==0) {
$contn = nl2br($contn);
}
Works perfectly for me.
Hope this is useful to someone else.

Related

Find a string that is not always the same [PHP]

I need help finding something in a variable that isn't always the same, and then put it in another variable.
I know that what I'm looking for has 5 slashes, it starts with steam://joingame/730/ and after the last slash there are 17 numbers.
Edit: It doesn't end with a slash, thats why I need to count 17 numbers after the fifth slash
Assuming what you're looking for looks something like this:
steam://joingame/730/11111111111111/
Then you could use explode() as a simple solution:
$gameId = explode('/', 'steam://joingame/730/11111111111111/');
var_dump($gameId[4]);
or you could use a regex as a more complex solution:
preg_match('|joingame/730/([0-9]+)|', 'steam://joingame/730/11111111111111/', $match);
var_dump($match[1]);
This splits the string into an array then return the last element as the game_id. It doesn't matter how many slashes. It will always return the last one.
$str = 'steam://joingame/730';
$arr = explode("/", $str) ;
$game_id = end($arr);
Following on from what DragonSpirit said
I modified there code so the string can look like
steam://joingame/730/11111111111111
or
steam://joingame/730/11111111111111/
$str = 'steam://joingame/730/11111111111111/';
$rstr = strrev( $str ); // reverses the string so it is now like /1111111111...
if($rstr[0] == "/") // checks if now first (was last ) character is a /
{
$nstr = substr($str, 0, -1); // if so it removes the /
}
else
{
$nstr = $str; // else it dont
}
$arr = explode("/", $nstr) ;
$game_id = end($arr);
Thanks for the help, I've found a solution for the problem. I'm going to post an uncommented version of the code on pastebin, becuase I couldn't get the code saple thing working here.
code

PHP keyword replacement using preg_replace and a FOR loop

I'm completely lost on what's wrong here. Any help will be appreciated.
I'm making a keyword replacement tool for a wordpress site. My problem is that my preg_replace seems to only run on the last element in the array when going through the post content.
The two get_options below are just textarea fields with each keyword and replacement on a separate line using character returns.
function keyword_replace($where) {
$keywords_to_replace = get_option('keywords_to_replace');
$keyword_links = get_option('keyword_links');
$KWs = explode("\n", $keywords_to_replace);
$URLs = explode("\n", $keyword_links);
$pattern = array();
$replacement = array();
for($i=0; $i< count($KWs); $i++) {
$pattern2 = '/<a[^>]*>(.*?)'.$KWs[$i].'(.*?)</a>/';
if(preg_match($pattern2, $where)) {
continue;
} else {
$pattern[$i] = '\'(?!((<.*?)|(<a.*?)))(\b'. $KWs[$i] . '\b)(?!(([^<>]*?)>)|([^>]*?</a>))\'si';
$replacement[$i] .= ''.$KWs[$i].'';
}
}
return preg_replace($pattern, $replacement, $where, -1);
}
add_filter('the_content','keyword_replace');
A var_dump() returns all the correct information, and nothing appears to be skipped in the dump. I'm stuck trying to figure out why it doesn't loop through the whole array.
Thanks for your help,
Rafael
I had a friend fix this for me. Just in case anyone else comes across a problem similar to mine, the fix was to use the trim() command around $KWs[$i] inside $pattern[$i].
$pattern[$i] = '\'(?!((<.*?)|(<a.*?)))(\b'. trim($KWs[$i]) . '\b)(?!(([^<>]*?)>)|([^>]*?</a>))\'si';
It all came down to windows vs. mac on character returns.

How can I make preg_replace only replace the first of *each* character matched?

For example, the following code wraps each matching character with an <i> tag.
echo preg_replace('/[aeiou]/', '<i>$0</i>', 'alphabet');
// result: <i>a</i>lph<i>a</i>b<i>e</i>t
But I'd like it to only replace each character once.
I'm looking for a result like <i>a</i>lphab<i>e</i>t, where the second a makes it through without a tag because the search string only has one a.
Can you help? Is this possible without of iterating through each character in an foreach loop?
The answer should also allow for two or more of the same characters, each only to be used once. For example, if I were searching for aaeioo in the string alphabetsoupisgood, it should match both of the a's but only two of the three o's.
If you just want a letter to be replaced only once then following regex should work:
echo preg_replace('/([aeiou])(?!.+?\\1)/', '<i>$1</i>', 'alphabet');
OUTPUT:
alph<i>a</i>b<i>e</i>t
PS: Note that it replaces last occurrence of a letter instead of the first one.
EDIT:
Following would produce the same output as expected by the OP (thanks to #AntonyHatchkins):
echo strrev(preg_replace
('/([aeiou])(?!.+?\\1)/', strrev('<i>1$</i>'), strrev('alphabet')))."\n";
EDIT 2:
Upon OP's comment:
Can you help me allow more than one a then? How can I match 2, but not 3 a's
I am posting this answer:
echo strrev(preg_replace('/([aeiou])(?!(.+?\\1){2})/',
strrev('<i>1$</i>'), strrev('alphabetax'))) . "\n";
EDIT 3:
Upon another of OP's comment:
that will allow duplicates for all characters in the string, not just 2 a's & 1 e
I am posting this answer:
echo strrev(preg_replace(array('/(a)(?!(.+?\\1){2})/',
'/(?<!>)([eiou])(?!.+?\\1)/'),
array(strrev('<i>1$</i>'), strrev('<i>1$</i>')), strrev('alphabetaxen')))."\n";
OUTPUT:
<i>a</i>lph<i>a</i>b<i>e</i>taxen
Note: I believe original problem has already changed so many times so please don't add further complexity in this problem. You're free to post another question if you have different queries.
Ugly but here's an approach.
echo
preg_replace('/a/','<i>$0</i>',
preg_replace('/e/','<i>$0</i>',
preg_replace('/i/','<i>$0</i>',
preg_replace('/o/','<i>$0</i>',
preg_replace('/u/','<i>$0</i>','alphabet',
1),1),1),1),1);
Use
echo preg_replace('/[aeiou]/', ' ', 'alphabet', 1);
Sorry i ansered before you edited your question
How about this.
$word = "alphabet";
$replace = array('a','e','i','o','u');
$with = array('','','','','');
echo str_replace($replace,$with,$word); //lphbt
According to http://php.net/manual/es/function.preg-replace.php, you can specify an additional parameter that limits the amount of replaces done.
Edit: Sorry, I didn't originally get your question. In that case, it's not possible. Due to the nature of Regex, it's not aware of the amount of replacements it has made. I might be wrong though, but I doubt that a regular expression exists that only makes one replacement per character.
Your best bet would be to make 5 calls, one each per character. Something like this:
$res = preg_replace('/a/', '<i>$0</i>', 'alphabet', 1);
$res = preg_replace('/e/', '<i>$0</i>', 'alphabet', 1);
$res = preg_replace('/i/', '<i>$0</i>', 'alphabet', 1);
$res = preg_replace('/o/', '<i>$0</i>', 'alphabet', 1);
$res = preg_replace('/u/', '<i>$0</i>', 'alphabet', 1);
echo $res;
Cheers
Here's another approach using the preg_replace_callback() function so I'm posting this as a brand new answer.
function replace_first($matches) {
static $used = array();
$key = $matches[0];
if (in_array($key,$used)) return $key;
$used[] = $key;
return '<i>' . $key . '</i>';
}
$str = preg_replace_callback('/[aeiou]/','replace_first','alphabet');
echo $str;
will output <i>a</i>lphab<i>e</i>t
The best I could do is loop through each character. (I try to avoid loops whenever possible) I wish there was a cleaner way, but this will do for now.
$word = 'alphabetsoupisgood';
$match = 'aaeou';
$wordArr = str_split($word);
$matchArr = str_split($capitals);
foreach ($matchArr as $c) {
$key = array_search($c, $wordArr);
if ($key !== false) {
$wordArr[$key] = strtoupper($c);
}
}
foreach ($wordArr as $k => $c) {
if (ctype_upper($c)) {
$wordArr[$k] = '<i>' . strtolower($c) . '</i>';
}
}
$word = implode('',$wordArr);
echo $word;
Here it is in codepad but they're running some super old version of PHP so ctype_upper isn't enabled... http://codepad.org/UoLWcK2S
If anyone can provide a cleaner answer using preg_replace I'd gladly mark yours as the answer.

Content Spinning using PHP?

Can anyone please help me? Say if I had this text or a smaller section stored in a variable, how can I randomise the words in the '{ }' ?
For example, the first one is "{important|essential|crucial|critical|vital|significant}" how can I make PHP choose one of those words randomly and then echo it? Thanks for helping me. :)
http://webarto.com/62/random-sentence-spinning-function
function get_random($matches)
{
$rand = array_rand($split = explode("|", $matches[1]));
return $split[$rand];
}
function show_randomized($str)
{
$new_str = preg_replace_callback('/\{([^{}]*)\}/im', "get_random", $str);
if ($new_str !== $str) $str = show_randomized($new_str);
return $str;
}
Applied on your text file... http://ideone.com/rkuf6
strip off initial and ending curly braces, you can use trim()
explode the resulting string on | using explode()
use array_rand() for the array you had in last step
Will not work with nested({a|x {b|c} y|z})!
function doStuff($from){
$to="";
while(($pos=strpos($from,'{'))!==false){
$to.=substr($from,0,$pos);
$from=substr($from,$pos);
$closepos=strpos($from,'}');
$arr=explode('|',substr($from,1,$closepos-1));
$to.=$arr[array_rand($arr)];
$from=substr($from,$closepos+1);
}
return $to.$from;
}

retrieving a parameter from a string

index.php?option=com_virtuemart&Itemid=210&category_id=12&lang=is&limit=20&limitstart=180&page=shop.browse
and I would like to retrieve the Page parameter from the string and if that page parameter is equal to "shop.browse" than return a true boolean.
edit: ps. the string does not always look like this but it does always contain the page= parameter
Ive been messing with strpos function and others and I can't get this working and I need this code quickly so if anyone can point me in there right direction of the best approach.
Thanks
Use parse_url first to get just the query part, then use parse_str to get the values:
$query = parse_url($str,PHP_URL_QUERY);
parse_str($query, $match);
if ($match['page'] === 'shop.browse') {
// page=shop.browse
}
Note that this assumes your string is stored in a variable $str.
Check the parse_url() function.
$str = explode("?",$url);
$str = explode("&",$str[1]);
foreach($str as $k=>$v) {
$xxx = explode("=",$v);
$output[$xxx[0]] = $output[$xxx[1]];
}
echo $output["page"];
this way you get all the parameters mapped to their keys. you obtain something like the $_GET/$_POST stuff is rendered.
the whole thing:
<?php
$url = "index.php?option=com_virtuemart&Itemid=210&category_id=12&lang=is&limit=20&limitstart=180&page=shop.browse";
$url = parse_url($url);
parse_str($url['query'], $output);
if($output['page'] == "shop.browse")
{
//stmts
}
else
{
//stmts
}

Categories