Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a UTF8 string that contains letters and digits. For example:
"Hello World 37. What? 24 last 6650"
and I want to reverse only the digits but keep the numbers in the same place.
The output should be:
"Hello World 73. What? 42 last 0566"
echo preg_replace_callback('/\d+/', function (array $m) { return strrev($m[0]); }, $string);
Before I posted the question, I thought about it and got an idea that works for me, so I'm only posting this question to enrich the database.
function reverseNumbersInString($str){
$tokens = explode(" ", $str);
$res = "";
for ($i = 0; $i < sizeof($tokens); $i++){
if (intval($tokens[$i] > 0 )){
$tokens[$i] = strrev($tokens[$i]);
}
$res .= " " . $tokens[$i];
}
return $res;
}
Maybe something like this:
$string = "Hello World 37. What? 24 last 6650";
preg_match_all('/\d+/', $string, $matches, PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $numberData) {
$numberArray = str_split($numberData[0]);
$reversedNumber = implode('', array_reverse($numberArray));
$string = substr_replace($string, $reversedNumber, $numberData[1], strlen($numberData[0]));
}
This should do it:
$stringWithReversedNumbers = preg_replace_callback(
'/\d+/',
function ($matches) {
return strrev($matches[0]);
},
$originalString
);
Alternatively, if you ONLY want to operate on numbers that are distinct words (i.e. not part of another word, as in if you want hello123goodbye to remain unmodified because the 123 isn't a word by itself), change \d+ to \b\d+\b
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Can someone provide a way to parse a field with a format like the following and take the difference between the two values between the colons.
bot1:11874-12227:top
For example, the resultant field would be equal to 12227-11874 = 353.
I think something like a scan by delimiter and then eval the negative of the difference.
$string = "bot1:11874-12227:top";
$parts = explode(":", $string);
$numbers = explode("-", $parts[1]);
$difference = (($numbers[1] - $numbers[0]) > 0) ? $numbers[1] - $numbers[0] : $numbers[0] - $numbers[1];
echo $difference;
Easy just use a regex with preg_match:
$string = 'bot1:11874-12227:top';
preg_match("#[A-Za-z]+[0-9]?:([0-9]+)([-|+|*|//])([0-9]+):[A-Za-z]+#", $string, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
The results would be:
Array
(
[0] => bot1:11874-12227:top
[1] => 11874
[2] => -
[3] => 12227
)
Then just do the following for the math:
echo abs($matches[1] - $matches[3]);
Now, note how $matches[2] matches the mathematical operator? Well, why not make use of that to do the following with create_function:
$string_to_math_results = create_function("", "return ($matches[1] $matches[2] $matches[3]);" );
echo abs($string_to_math_results());
So bring it all together like this. Now you can not only parse the values out of the string, but perform basic calculations based on the value in the strings:
$string = 'bot1:11874-12227:top';
preg_match("#[A-Za-z]+[0-9]?:([0-9]+)([-|+|*|//])([0-9]+):[A-Za-z]+#", $string, $matches);
$string_to_math_results = create_function("", "return ($matches[1] - $matches[3]);" );
echo abs($string_to_math_results());
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am getting Output value like 0.000098, 0.000854.
But I need 98, 854 instead.
How to do this?
<?php
$str = '0.00009801';
$r = array();
$ret = preg_match('/[1-9]+[0-9]+/', $str, $r);
echo $r[0];
You can use
$num = '0.000098000';
$newNum = preg_replace('/^[0\.]+/', '', $num);
The $newNum will contain the required output (98000 in the case above) after replacing all the 0 and . from the starting.
So you want to take a string, split it by a comma and remove spaces , multiply by 1000000 then put it back together. Try doing this:
$str = "0.000098, 0.000854";
echo implode(",",array_map(function($a){ return 1000000 * trim($a); },explode(",", $str)));
or in a slightly more readable form:
$parts = explode(",", $str);
$parts = array_map(function($a) { return 1000000 * trim($a); }, $parts);
echo implode(",", $parts);
function convertVal($value) {
for($i=0;$i<strlen($value);$i++){
$a = strpos($value,substr($value,$i,$i+1));
if($a>0){
$pos = substr($value,$a-1,strlen($value));
}
}
return $pos;
}
echo convertVal("0000980");
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
If the first word of a sentence is "The" I want to replace it to the end with a comma before it so for example if I have the movie title: The Hunger Games, I want it to become: Hunger Games, The
Is this possible and if it is how can I get it working?
Please try this:
<?
$str = 'The Hunger Games';
if (strtolower(substr($str,0,3)) == "the"){
$str = trim(substr($str,3)).', The';
}
echo $str;
?>
WORKING CODE
Use:
echo custom_func('The Hunger Games');
Function:
function custom_func($s) {
$s = trim(preg_replace('~\s+~', ' ', $s));
$a = explode(' ', $s);
if (strtolower($a[0]) != 'the' || count($a) < 2) return $s;
$the = array_shift($a);
return implode(' ', $a) . ', ' . $the;
}
Demo.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Need to transform
PROP_RESOURCE_TYPE
to
propResourceType
or
setPropResourceType
Number of _ and string length are not fixed.
I'm not really into preg_replace,
could you help me out
lcfirst(implode(array_map('ucfirst', explode('_', strtolower($str)))));
For completeness, an example of how a regular expression could help:
// match each underscore followed by a letter
echo preg_replace_callback('/_([a-z])/', function($m) {
return strtoupper($m[1]); // upper case the letter
}, strtolower('PROP_RESOURCE_TYPE'));
One possible solution:
<?php
$step1 = strtolower("PROP_RESOURCE_TYPE"); // prop_resource_type
$step2 = str_replace("_"," ",$step1); // prop resource type
$step3 = ucwords($step2); // Prop Resource Type
$step4 = str_replace(" ","",$step3); // PropResourceType
$step5 = "set".$step4;
?>
For additional completeness, an example of how a regular expression could help:
$subject = 'PROP_RESOURCE_TYPE';
// match uppercase varnames
echo preg_replace_callback('/[A-Z]+(?:_[A-Z]+)+/', function ($matches) {
list($varName) = $matches;
$varName = strtolower($varName);
$varName = strtr($varName, '_', ' ');
$varName = ucwords($varName);
$varName = strtr($varName, [' ' => '']);
$varName = 'set' . $varName;
// or:
// $varName[0] = strtolower($varName[0]);
return $varName;
}, $subject);
// php 5.3.0+
$initial = 'PROP_RESOURCE_TYPE';
$words = explode('_', $initial);
foreach($words as &$word){
$word = ucfirst(strtolower($word));
}
$final = implode($words);
echo $final;
// returns PropResourceType
// if you want a lowercase first letter just do
echo lcfirst($final);
// returns propResourceType
another solution
echo preg_replace("/_([a-z])/e", 'strtoupper("$1")', strtolower($str));
EDIT e modifier has been deprecated as of PHP 5.5.0, so be carefull
EDIT2 #hakre was so angry, that I decided to mention, that the only problem is: e can cause E_DEPRECATED level error (usually, turned off on all production servers). Anyway it still works on all PHP versions
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to replace keywords such as "the", "and" etc.. in headings and replace it with a span in the heading tags.
Ex:
<h2>This is the heading</h2>
to become
<h2>This is <span>the</span> heading</h2>
Thanks for any help
UPDATE
I found something that works for what I had wanted:
$(function() {
$('h2').each(function(i, elem) {
$(elem).html(function(i, html) {
return html.replace(/the/, "<span>the</span>");
});
});
});
A PHP only solution (without regex):
$string = "<h2>This is the heading</h2>";
$toReplace = array("the", "and");
$replaceTo = array_map(function ($val) { return "<span>$val</span>"; }, $toReplace);
$newString = str_replace($toReplace, $replaceTo, $string);
print $newString; // prints as expected: <h2>This is <span>the</span> heading</h2>
This code will help you do it and extend your words dynamically:
$special_words = array("the", "and", "or") ;
$words = implode("|", $special_words) ;
$string = "<h2>This is the heading</h2>" ;
$new = preg_replace("/({$words})/i", "<span>$1</span>", $string) ;
echo $new ;
very easy with regexp, this example only use one keyword, for multiple keywords use an array.
$string = "<h2>This is the heading</h2>";
$string = preg_replace("/(the|end)/", "<span>$1</span>", $string);