Jump to content

Words in a string


gerkintrigg

Recommended Posts

Hello.

 

I'm trying to work out how to get certain words from a text string into an array.

 

Essentially, I want to take all words beginning with a $ symbol from an HTML file and bung them into an array for processing. This way, I can have people upload HTML files and my PHP project can replace them with other stuff (like names, input boxes etc).

 

I know the explode command and could loop through to split at the $ symbol, then loop through to break at the following space character, but it seems a long-winded way of doing it.

 

Thanks in advance.

Link to comment
Share on other sites

I think i understand the premise, but I don't want to print the words, but put them into an array and as I'm not familiar with your way of matching the string (preg_match always seems so impenetrable), I'm not sure how to do this.

 

I tried using a foreach loop:

 

<?php

$strTest = '$this is $best a test';

preg_match_all("~\\\$([\w\d]+)?~",$strTest,$arrMatches);
print_r($arrMatches[0]);
foreach ($arrMatches[0] as $key => $value){
echo $value[$key];
}


?>

Link to comment
Share on other sites

well for your first answer the code should be

 

<?php

$strTest = '$this is $best a test';

preg_match_all("~\\\$([\w\d]+)?~",$strTest,$arrMatches);
print_r($arrMatches[0]);
foreach ($arrMatches[0] as $key => $value){
echo $value;
}


?>

 

 

better still consider this following code

 

 

<?php

$arrData = array("username"=>"rajivgonsalves","email"=>"rajivgonsalves@yahoo.com");
$strTest = 'Your username is $username and your email is $email';

$strTest = preg_replace("~\\\$([\w\d]+)?~e","\$arrData['$1']",$strTest);
echo $strTest;
?>

Link to comment
Share on other sites

Hi. Thanks for that. I got this to work:

$strTest = '$this is $best a test';

preg_match_all("~\\\$([\w\d]+)?~",$strTest,$arrMatches);
$my_array =$arrMatches[0];
foreach ($my_array as $key => $value){
echo $value;
}

for some reason, using an array delimiter doesn't seem to work in a foreach loop eg: foreach ($arrMatches[0] as $key => $value){

so i needed to put the array into a different variable.

 

but thanks for the details - It's very useful.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.