preg_replace pass match through function before replacing - php

This is what i want to do:
$line = 'blabla translate("test") blabla';
$line = preg_replace("/(.*?)translate\((.*?)\)(.*?)/","$1".translate("$2")."$3",$line);
So the result should be that translate("test") is replaced with the translation of "test".
The problem is that translate("$2") passes the string "$2" to the translate function. So translate() tries to translate "$2" instead of "test".
Is there some way to pass the value of the match to a function before replacing?

preg_replace_callback is your friend
function translate($m) {
$x = process $m[1];
return $x;
}
$line = preg_replace_callback("/translate\((.*?)\)/", 'translate', $line);

You can use the preg_replace_callback function as:
$line = 'blabla translate("test") blabla';
$line = preg_replace_callback("/(.*?)translate\((.*?)\)(.*?)/",fun,$line);
function fun($matches) {
return $matches[1].translate($matches[2]).$matches[3];
}

Related

PHP search for string in text file & return result after specific character

i want search string in text file. find result and return after : character.
input is alex
text file include this item
alex:+123
david:+1345
john:+1456
output is +123
$input = "alex";
file_get_contents("TextFilePath");
//in this step i don't know what should i do
Maybe not the best solution, but you can use file and loop on the array. explode each line to see if the needle was present.
function findInAFile($filename, $needle) {
// read file split on newline
$lines = file($filename);
// check each line and return first occurence
foreach ($lines as $line) {
$arr = explode($needle, $line, 2);
if (isset($arr[1])) {
return $arr[1];
}
}
}
echo findInAFile('file.txt', $input.':');
You can use a regular expression match to locate lines beginning with the given input:
$input = "alex";
$text = file_get_contents("TextFilePath");
if (preg_match('#^' . preg_quote($input) . ':(.*)#m', $text, $match) {
// Found input
var_dump($match[1]);
}

Creating a function to act on many variables

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;
?>

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

PHP preg match?

Okay, let's say this is a line
v1=something;v2=something2;
how to get v1 value (something) starting from = and break at ; and same to be done with v2 by calling it (v1)
function getVal($name){
// some code to start grabbing from = and end by ;
}
when i call
getVal("v1");
it should return "something"
This will work
v1=([^;]*)
The match will be in group 1
Just replace v1 in the regex with the key you want to lookup
if (preg_match('/v1=([^;]*)/', $subject, $regs)) {
$result = $regs[1];
} else {
$result = "";
}
If I understand your question, then I think this is what you are looking for:
$line = "v1=something;v2=something2;";
function getVal($name, $line){
preg_match('/'.$name.'=([^;]*)/', $line, $matches);
return $matches[1];
}
echo getVal("v1", $line);
v(?:\d*)=(\w;+)
That will match all v (with digits or no digits after it) and then the match group will be after the = sign. It is group 1.
You are obliged to sent the line to your function (or you can be dirty and use it as global).
So, your function can be something like that :
<?php
function getVal($name, $line){
// some code to start grabbing from = and end by ;
preg_match('#;?' . $name . '=([^;]+);?#', $line, $aMatches);
if(isset($aMatches[1])) {
return $aMatches[1];
}
return false;
}
$line = 'v1=something;v2=something2';
$v1 = getVal('v1',$line);
echo $v1;
?>
Use this Function:
function getVal($name, $line){
preg_match("/{$name}=(.+);(v(\d+)=|$)/U", $line, $matches);
$matches = $matches[0];
$matches = preg_replace("/{$name}=/","",$matches);
$matches = preg_replace("/;v(\d+)=/","",$matches);
return $matches;
}
this will give you exact answer.
Tested and working.:)

PHP extract text from string - trim?

I have the following XML:
<id>tag:search.twitter.com,2005:22204349686</id>
How can i write everything after the second colon to a variable?
E.g. 22204349686
if(preg_match('#<id>.*?:.*?:(.*?)</id>#',$input,$m)) {
$num = $m[1];
}
When you already have just the tags content in a variable $str, you could use explode to get everything from the second : on:
list(,,$rest) = explode(':', $str, 3);
$var = preg_replace('/^([^:]+:){2}/', '', 'tag:search.twitter.com,2005:22204349686');
I am assuming you already have the string without the <id> bits.
Otherwise, for SimpleXML:
$var = preg_replace('/^([^:]+:){2}/', '', "{$yourXml->id}");
First, parse the XML with an XML parser. Find the text content of the node in question (tag:search.twitter.com,2005:22204349686). Then, write a relevant regex, e.g.
<?php
$str = 'tag:search.twitter.com,2005:22204349686';
preg_match('#^([^:]+):([^,]+),([0-9]+):([0-9]+)#', $str, $matches);
var_dump($matches);
I suppose you have in a variable ($str) the content of id tag.
// get last occurence of colon
$pos = strrpos($str, ":");
if ($pos !== false) {
// get substring of $str from position $pos to the end of $str
$result = substr($str, $pos);
} else {
$result = null;
}
Regex seems to me inappropriate for such a simple matching.
If you dont have the ID tags around the string, you can simply do
echo trim(strrchr($xml, ':'), ':');
If they are around, you can use
$xml = '<id>tag:search.twitter.com,2005:22204349686</id>';
echo filter_var(strrchr($xml, ':'), FILTER_SANITIZE_NUMBER_INT);
// 22204349686
The strrchr part returns :22204349686</id> and the filter_var part strips everything that's not a number.
Use explode and strip_tags:
list(,,$id) = explode( ':', strip_tags( $input ), 3 );
function between($t1,$t2,$page) {
$p1=stripos($page,$t1);
if($p1!==false) {
$p2=stripos($page,$t2,$p1+strlen($t1));
} else {
return false;
}
return substr($page,$p1+strlen($t1),$p2-$p1-strlen($t1));
}
$x='<id>tag:search.twitter.com,2005:22204349686</id>';
$text=between(',','<',$x);
if($text!==false) {
//got some text..
}

Categories